]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/adapters/mod.rs
mark as_inner as unsafe and update comments
[rust.git] / library / core / src / iter / adapters / mod.rs
1 use crate::cmp;
2 use crate::fmt;
3 use crate::intrinsics;
4 use crate::ops::{Add, AddAssign, ControlFlow, Try};
5
6 use super::from_fn;
7 use super::{
8     DoubleEndedIterator, ExactSizeIterator, FusedIterator, InPlaceIterable, Iterator, TrustedLen,
9 };
10
11 mod chain;
12 mod flatten;
13 mod fuse;
14 mod zip;
15
16 pub use self::chain::Chain;
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub use self::flatten::{FlatMap, Flatten};
19 pub use self::fuse::Fuse;
20 use self::zip::try_get_unchecked;
21 #[unstable(feature = "trusted_random_access", issue = "none")]
22 pub use self::zip::TrustedRandomAccess;
23 pub use self::zip::Zip;
24
25 /// This trait provides transitive access to source-stage in an interator-adapter pipeline
26 /// under the conditions that
27 /// * the iterator source `S` itself implements `SourceIter<Source = S>`
28 /// * there is a delegating implementation of this trait for each adapter in the pipeline between
29 ///   the source and the pipeline consumer.
30 ///
31 /// When the source is an owning iterator struct (commonly called `IntoIter`) then
32 /// this can be useful for specializing [`FromIterator`] implementations or recovering the
33 /// remaining elements after an iterator has been partially exhausted.
34 ///
35 /// Note that implementations do not necessarily have to provide access to the inner-most
36 /// source of a pipeline. A stateful intermediate adapter might eagerly evaluate a part
37 /// of the pipeline and expose its internal storage as source.
38 ///
39 /// The trait is unsafe because implementers must uphold additional safety properties.
40 /// See [`as_inner`] for details.
41 ///
42 /// # Examples
43 ///
44 /// Retrieving a partially consumed source:
45 ///
46 /// ```
47 /// # #![feature(inplace_iteration)]
48 /// # use std::iter::SourceIter;
49 ///
50 /// let mut iter = vec![9, 9, 9].into_iter().map(|i| i * i);
51 /// let _ = iter.next();
52 /// let mut remainder = std::mem::replace(unsafe { iter.as_inner() }, Vec::new().into_iter());
53 /// println!("n = {} elements remaining", remainder.len());
54 /// ```
55 ///
56 /// [`FromIterator`]: crate::iter::FromIterator
57 /// [`as_inner`]: SourceIter::as_inner
58 #[unstable(issue = "0", feature = "inplace_iteration")]
59 pub unsafe trait SourceIter {
60     /// A source stage in an iterator pipeline.
61     type Source: Iterator;
62
63     /// Retrieve the source of an iterator pipeline.
64     ///
65     /// # Safety
66     ///
67     /// Implementations of must return the same mutable reference for their lifetime, unless
68     /// replaced by a caller.
69     /// Callers may only replace the reference when they stopped iteration and drop the
70     /// iterator pipeline after extracting the source.
71     ///
72     /// This means iterator adapters can rely on the source not changing during
73     /// iteration but they cannot rely on it in their Drop implementations.
74     ///
75     /// Implementing this method means adapters relinquish private-only access to their
76     /// source and can only rely on guarantees made based on method receiver types.
77     /// The lack of restricted access also requires that adapters must uphold the source's
78     /// public API even when they have access to its internals.
79     ///
80     /// Callers in turn must expect the source to be in any state that is consistent with
81     /// its public API since adapters sitting between it and the source have the same
82     /// access. In particular an adapter may have consumed more elements than strictly necessary.
83     ///
84     /// The overall goal of these requirements is to let the consumer of a pipeline use
85     /// * whatever remains in the source after iteration has stopped
86     /// * the memory that has become unused by advancing a consuming iterator
87     ///
88     /// [`next()`]: trait.Iterator.html#method.next
89     unsafe fn as_inner(&mut self) -> &mut Self::Source;
90 }
91
92 /// A double-ended iterator with the direction inverted.
93 ///
94 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
95 /// documentation for more.
96 ///
97 /// [`rev`]: trait.Iterator.html#method.rev
98 /// [`Iterator`]: trait.Iterator.html
99 #[derive(Clone, Debug)]
100 #[must_use = "iterators are lazy and do nothing unless consumed"]
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub struct Rev<T> {
103     iter: T,
104 }
105 impl<T> Rev<T> {
106     pub(super) fn new(iter: T) -> Rev<T> {
107         Rev { iter }
108     }
109 }
110
111 #[stable(feature = "rust1", since = "1.0.0")]
112 impl<I> Iterator for Rev<I>
113 where
114     I: DoubleEndedIterator,
115 {
116     type Item = <I as Iterator>::Item;
117
118     #[inline]
119     fn next(&mut self) -> Option<<I as Iterator>::Item> {
120         self.iter.next_back()
121     }
122     #[inline]
123     fn size_hint(&self) -> (usize, Option<usize>) {
124         self.iter.size_hint()
125     }
126
127     #[inline]
128     fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
129         self.iter.nth_back(n)
130     }
131
132     fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
133     where
134         Self: Sized,
135         F: FnMut(B, Self::Item) -> R,
136         R: Try<Ok = B>,
137     {
138         self.iter.try_rfold(init, f)
139     }
140
141     fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
142     where
143         F: FnMut(Acc, Self::Item) -> Acc,
144     {
145         self.iter.rfold(init, f)
146     }
147
148     #[inline]
149     fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
150     where
151         P: FnMut(&Self::Item) -> bool,
152     {
153         self.iter.rfind(predicate)
154     }
155 }
156
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<I> DoubleEndedIterator for Rev<I>
159 where
160     I: DoubleEndedIterator,
161 {
162     #[inline]
163     fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
164         self.iter.next()
165     }
166
167     #[inline]
168     fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item> {
169         self.iter.nth(n)
170     }
171
172     fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
173     where
174         Self: Sized,
175         F: FnMut(B, Self::Item) -> R,
176         R: Try<Ok = B>,
177     {
178         self.iter.try_fold(init, f)
179     }
180
181     fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
182     where
183         F: FnMut(Acc, Self::Item) -> Acc,
184     {
185         self.iter.fold(init, f)
186     }
187
188     fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
189     where
190         P: FnMut(&Self::Item) -> bool,
191     {
192         self.iter.find(predicate)
193     }
194 }
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<I> ExactSizeIterator for Rev<I>
198 where
199     I: ExactSizeIterator + DoubleEndedIterator,
200 {
201     fn len(&self) -> usize {
202         self.iter.len()
203     }
204
205     fn is_empty(&self) -> bool {
206         self.iter.is_empty()
207     }
208 }
209
210 #[stable(feature = "fused", since = "1.26.0")]
211 impl<I> FusedIterator for Rev<I> where I: FusedIterator + DoubleEndedIterator {}
212
213 #[unstable(feature = "trusted_len", issue = "37572")]
214 unsafe impl<I> TrustedLen for Rev<I> where I: TrustedLen + DoubleEndedIterator {}
215
216 /// An iterator that copies the elements of an underlying iterator.
217 ///
218 /// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
219 /// documentation for more.
220 ///
221 /// [`copied`]: trait.Iterator.html#method.copied
222 /// [`Iterator`]: trait.Iterator.html
223 #[stable(feature = "iter_copied", since = "1.36.0")]
224 #[must_use = "iterators are lazy and do nothing unless consumed"]
225 #[derive(Clone, Debug)]
226 pub struct Copied<I> {
227     it: I,
228 }
229
230 impl<I> Copied<I> {
231     pub(super) fn new(it: I) -> Copied<I> {
232         Copied { it }
233     }
234 }
235
236 fn copy_fold<T: Copy, Acc>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc {
237     move |acc, &elt| f(acc, elt)
238 }
239
240 fn copy_try_fold<T: Copy, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
241     move |acc, &elt| f(acc, elt)
242 }
243
244 #[stable(feature = "iter_copied", since = "1.36.0")]
245 impl<'a, I, T: 'a> Iterator for Copied<I>
246 where
247     I: Iterator<Item = &'a T>,
248     T: Copy,
249 {
250     type Item = T;
251
252     fn next(&mut self) -> Option<T> {
253         self.it.next().copied()
254     }
255
256     fn size_hint(&self) -> (usize, Option<usize>) {
257         self.it.size_hint()
258     }
259
260     fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
261     where
262         Self: Sized,
263         F: FnMut(B, Self::Item) -> R,
264         R: Try<Ok = B>,
265     {
266         self.it.try_fold(init, copy_try_fold(f))
267     }
268
269     fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
270     where
271         F: FnMut(Acc, Self::Item) -> Acc,
272     {
273         self.it.fold(init, copy_fold(f))
274     }
275
276     fn nth(&mut self, n: usize) -> Option<T> {
277         self.it.nth(n).copied()
278     }
279
280     fn last(self) -> Option<T> {
281         self.it.last().copied()
282     }
283
284     fn count(self) -> usize {
285         self.it.count()
286     }
287
288     unsafe fn get_unchecked(&mut self, idx: usize) -> T
289     where
290         Self: TrustedRandomAccess,
291     {
292         // SAFETY: the caller must uphold the contract for
293         // `Iterator::get_unchecked`.
294         *unsafe { try_get_unchecked(&mut self.it, idx) }
295     }
296 }
297
298 #[stable(feature = "iter_copied", since = "1.36.0")]
299 impl<'a, I, T: 'a> DoubleEndedIterator for Copied<I>
300 where
301     I: DoubleEndedIterator<Item = &'a T>,
302     T: Copy,
303 {
304     fn next_back(&mut self) -> Option<T> {
305         self.it.next_back().copied()
306     }
307
308     fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
309     where
310         Self: Sized,
311         F: FnMut(B, Self::Item) -> R,
312         R: Try<Ok = B>,
313     {
314         self.it.try_rfold(init, copy_try_fold(f))
315     }
316
317     fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
318     where
319         F: FnMut(Acc, Self::Item) -> Acc,
320     {
321         self.it.rfold(init, copy_fold(f))
322     }
323 }
324
325 #[stable(feature = "iter_copied", since = "1.36.0")]
326 impl<'a, I, T: 'a> ExactSizeIterator for Copied<I>
327 where
328     I: ExactSizeIterator<Item = &'a T>,
329     T: Copy,
330 {
331     fn len(&self) -> usize {
332         self.it.len()
333     }
334
335     fn is_empty(&self) -> bool {
336         self.it.is_empty()
337     }
338 }
339
340 #[stable(feature = "iter_copied", since = "1.36.0")]
341 impl<'a, I, T: 'a> FusedIterator for Copied<I>
342 where
343     I: FusedIterator<Item = &'a T>,
344     T: Copy,
345 {
346 }
347
348 #[doc(hidden)]
349 #[unstable(feature = "trusted_random_access", issue = "none")]
350 unsafe impl<I> TrustedRandomAccess for Copied<I>
351 where
352     I: TrustedRandomAccess,
353 {
354     #[inline]
355     fn may_have_side_effect() -> bool {
356         I::may_have_side_effect()
357     }
358 }
359
360 #[stable(feature = "iter_copied", since = "1.36.0")]
361 unsafe impl<'a, I, T: 'a> TrustedLen for Copied<I>
362 where
363     I: TrustedLen<Item = &'a T>,
364     T: Copy,
365 {
366 }
367
368 /// An iterator that clones the elements of an underlying iterator.
369 ///
370 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
371 /// documentation for more.
372 ///
373 /// [`cloned`]: trait.Iterator.html#method.cloned
374 /// [`Iterator`]: trait.Iterator.html
375 #[stable(feature = "iter_cloned", since = "1.1.0")]
376 #[must_use = "iterators are lazy and do nothing unless consumed"]
377 #[derive(Clone, Debug)]
378 pub struct Cloned<I> {
379     it: I,
380 }
381 impl<I> Cloned<I> {
382     pub(super) fn new(it: I) -> Cloned<I> {
383         Cloned { it }
384     }
385 }
386
387 fn clone_try_fold<T: Clone, Acc, R>(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R {
388     move |acc, elt| f(acc, elt.clone())
389 }
390
391 #[stable(feature = "iter_cloned", since = "1.1.0")]
392 impl<'a, I, T: 'a> Iterator for Cloned<I>
393 where
394     I: Iterator<Item = &'a T>,
395     T: Clone,
396 {
397     type Item = T;
398
399     fn next(&mut self) -> Option<T> {
400         self.it.next().cloned()
401     }
402
403     fn size_hint(&self) -> (usize, Option<usize>) {
404         self.it.size_hint()
405     }
406
407     fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
408     where
409         Self: Sized,
410         F: FnMut(B, Self::Item) -> R,
411         R: Try<Ok = B>,
412     {
413         self.it.try_fold(init, clone_try_fold(f))
414     }
415
416     fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
417     where
418         F: FnMut(Acc, Self::Item) -> Acc,
419     {
420         self.it.map(T::clone).fold(init, f)
421     }
422
423     unsafe fn get_unchecked(&mut self, idx: usize) -> T
424     where
425         Self: TrustedRandomAccess,
426     {
427         // SAFETY: the caller must uphold the contract for
428         // `Iterator::get_unchecked`.
429         unsafe { try_get_unchecked(&mut self.it, idx).clone() }
430     }
431 }
432
433 #[stable(feature = "iter_cloned", since = "1.1.0")]
434 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
435 where
436     I: DoubleEndedIterator<Item = &'a T>,
437     T: Clone,
438 {
439     fn next_back(&mut self) -> Option<T> {
440         self.it.next_back().cloned()
441     }
442
443     fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
444     where
445         Self: Sized,
446         F: FnMut(B, Self::Item) -> R,
447         R: Try<Ok = B>,
448     {
449         self.it.try_rfold(init, clone_try_fold(f))
450     }
451
452     fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
453     where
454         F: FnMut(Acc, Self::Item) -> Acc,
455     {
456         self.it.map(T::clone).rfold(init, f)
457     }
458 }
459
460 #[stable(feature = "iter_cloned", since = "1.1.0")]
461 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
462 where
463     I: ExactSizeIterator<Item = &'a T>,
464     T: Clone,
465 {
466     fn len(&self) -> usize {
467         self.it.len()
468     }
469
470     fn is_empty(&self) -> bool {
471         self.it.is_empty()
472     }
473 }
474
475 #[stable(feature = "fused", since = "1.26.0")]
476 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
477 where
478     I: FusedIterator<Item = &'a T>,
479     T: Clone,
480 {
481 }
482
483 #[doc(hidden)]
484 #[unstable(feature = "trusted_random_access", issue = "none")]
485 unsafe impl<I> TrustedRandomAccess for Cloned<I>
486 where
487     I: TrustedRandomAccess,
488
489 {
490     #[inline]
491     fn may_have_side_effect() -> bool {
492         true
493     }
494 }
495
496 #[unstable(feature = "trusted_len", issue = "37572")]
497 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
498 where
499     I: TrustedLen<Item = &'a T>,
500     T: Clone,
501 {
502 }
503
504 /// An iterator that repeats endlessly.
505 ///
506 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
507 /// documentation for more.
508 ///
509 /// [`cycle`]: trait.Iterator.html#method.cycle
510 /// [`Iterator`]: trait.Iterator.html
511 #[derive(Clone, Debug)]
512 #[must_use = "iterators are lazy and do nothing unless consumed"]
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub struct Cycle<I> {
515     orig: I,
516     iter: I,
517 }
518 impl<I: Clone> Cycle<I> {
519     pub(super) fn new(iter: I) -> Cycle<I> {
520         Cycle { orig: iter.clone(), iter }
521     }
522 }
523
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl<I> Iterator for Cycle<I>
526 where
527     I: Clone + Iterator,
528 {
529     type Item = <I as Iterator>::Item;
530
531     #[inline]
532     fn next(&mut self) -> Option<<I as Iterator>::Item> {
533         match self.iter.next() {
534             None => {
535                 self.iter = self.orig.clone();
536                 self.iter.next()
537             }
538             y => y,
539         }
540     }
541
542     #[inline]
543     fn size_hint(&self) -> (usize, Option<usize>) {
544         // the cycle iterator is either empty or infinite
545         match self.orig.size_hint() {
546             sz @ (0, Some(0)) => sz,
547             (0, _) => (0, None),
548             _ => (usize::MAX, None),
549         }
550     }
551
552     #[inline]
553     fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
554     where
555         F: FnMut(Acc, Self::Item) -> R,
556         R: Try<Ok = Acc>,
557     {
558         // fully iterate the current iterator. this is necessary because
559         // `self.iter` may be empty even when `self.orig` isn't
560         acc = self.iter.try_fold(acc, &mut f)?;
561         self.iter = self.orig.clone();
562
563         // complete a full cycle, keeping track of whether the cycled
564         // iterator is empty or not. we need to return early in case
565         // of an empty iterator to prevent an infinite loop
566         let mut is_empty = true;
567         acc = self.iter.try_fold(acc, |acc, x| {
568             is_empty = false;
569             f(acc, x)
570         })?;
571
572         if is_empty {
573             return Try::from_ok(acc);
574         }
575
576         loop {
577             self.iter = self.orig.clone();
578             acc = self.iter.try_fold(acc, &mut f)?;
579         }
580     }
581
582     // No `fold` override, because `fold` doesn't make much sense for `Cycle`,
583     // and we can't do anything better than the default.
584 }
585
586 #[stable(feature = "fused", since = "1.26.0")]
587 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
588
589 /// An iterator for stepping iterators by a custom amount.
590 ///
591 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
592 /// its documentation for more.
593 ///
594 /// [`step_by`]: trait.Iterator.html#method.step_by
595 /// [`Iterator`]: trait.Iterator.html
596 #[must_use = "iterators are lazy and do nothing unless consumed"]
597 #[stable(feature = "iterator_step_by", since = "1.28.0")]
598 #[derive(Clone, Debug)]
599 pub struct StepBy<I> {
600     iter: I,
601     step: usize,
602     first_take: bool,
603 }
604 impl<I> StepBy<I> {
605     pub(super) fn new(iter: I, step: usize) -> StepBy<I> {
606         assert!(step != 0);
607         StepBy { iter, step: step - 1, first_take: true }
608     }
609 }
610
611 #[stable(feature = "iterator_step_by", since = "1.28.0")]
612 impl<I> Iterator for StepBy<I>
613 where
614     I: Iterator,
615 {
616     type Item = I::Item;
617
618     #[inline]
619     fn next(&mut self) -> Option<Self::Item> {
620         if self.first_take {
621             self.first_take = false;
622             self.iter.next()
623         } else {
624             self.iter.nth(self.step)
625         }
626     }
627
628     #[inline]
629     fn size_hint(&self) -> (usize, Option<usize>) {
630         #[inline]
631         fn first_size(step: usize) -> impl Fn(usize) -> usize {
632             move |n| if n == 0 { 0 } else { 1 + (n - 1) / (step + 1) }
633         }
634
635         #[inline]
636         fn other_size(step: usize) -> impl Fn(usize) -> usize {
637             move |n| n / (step + 1)
638         }
639
640         let (low, high) = self.iter.size_hint();
641
642         if self.first_take {
643             let f = first_size(self.step);
644             (f(low), high.map(f))
645         } else {
646             let f = other_size(self.step);
647             (f(low), high.map(f))
648         }
649     }
650
651     #[inline]
652     fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
653         if self.first_take {
654             self.first_take = false;
655             let first = self.iter.next();
656             if n == 0 {
657                 return first;
658             }
659             n -= 1;
660         }
661         // n and self.step are indices, we need to add 1 to get the amount of elements
662         // When calling `.nth`, we need to subtract 1 again to convert back to an index
663         // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
664         let mut step = self.step + 1;
665         // n + 1 could overflow
666         // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
667         if n == usize::MAX {
668             self.iter.nth(step - 1);
669         } else {
670             n += 1;
671         }
672
673         // overflow handling
674         loop {
675             let mul = n.checked_mul(step);
676             {
677                 if intrinsics::likely(mul.is_some()) {
678                     return self.iter.nth(mul.unwrap() - 1);
679                 }
680             }
681             let div_n = usize::MAX / n;
682             let div_step = usize::MAX / step;
683             let nth_n = div_n * n;
684             let nth_step = div_step * step;
685             let nth = if nth_n > nth_step {
686                 step -= div_n;
687                 nth_n
688             } else {
689                 n -= div_step;
690                 nth_step
691             };
692             self.iter.nth(nth - 1);
693         }
694     }
695
696     fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
697     where
698         F: FnMut(Acc, Self::Item) -> R,
699         R: Try<Ok = Acc>,
700     {
701         #[inline]
702         fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
703             move || iter.nth(step)
704         }
705
706         if self.first_take {
707             self.first_take = false;
708             match self.iter.next() {
709                 None => return Try::from_ok(acc),
710                 Some(x) => acc = f(acc, x)?,
711             }
712         }
713         from_fn(nth(&mut self.iter, self.step)).try_fold(acc, f)
714     }
715
716     fn fold<Acc, F>(mut self, mut acc: Acc, mut f: F) -> Acc
717     where
718         F: FnMut(Acc, Self::Item) -> Acc,
719     {
720         #[inline]
721         fn nth<I: Iterator>(iter: &mut I, step: usize) -> impl FnMut() -> Option<I::Item> + '_ {
722             move || iter.nth(step)
723         }
724
725         if self.first_take {
726             self.first_take = false;
727             match self.iter.next() {
728                 None => return acc,
729                 Some(x) => acc = f(acc, x),
730             }
731         }
732         from_fn(nth(&mut self.iter, self.step)).fold(acc, f)
733     }
734 }
735
736 impl<I> StepBy<I>
737 where
738     I: ExactSizeIterator,
739 {
740     // The zero-based index starting from the end of the iterator of the
741     // last element. Used in the `DoubleEndedIterator` implementation.
742     fn next_back_index(&self) -> usize {
743         let rem = self.iter.len() % (self.step + 1);
744         if self.first_take {
745             if rem == 0 { self.step } else { rem - 1 }
746         } else {
747             rem
748         }
749     }
750 }
751
752 #[stable(feature = "double_ended_step_by_iterator", since = "1.38.0")]
753 impl<I> DoubleEndedIterator for StepBy<I>
754 where
755     I: DoubleEndedIterator + ExactSizeIterator,
756 {
757     #[inline]
758     fn next_back(&mut self) -> Option<Self::Item> {
759         self.iter.nth_back(self.next_back_index())
760     }
761
762     #[inline]
763     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
764         // `self.iter.nth_back(usize::MAX)` does the right thing here when `n`
765         // is out of bounds because the length of `self.iter` does not exceed
766         // `usize::MAX` (because `I: ExactSizeIterator`) and `nth_back` is
767         // zero-indexed
768         let n = n.saturating_mul(self.step + 1).saturating_add(self.next_back_index());
769         self.iter.nth_back(n)
770     }
771
772     fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R
773     where
774         F: FnMut(Acc, Self::Item) -> R,
775         R: Try<Ok = Acc>,
776     {
777         #[inline]
778         fn nth_back<I: DoubleEndedIterator>(
779             iter: &mut I,
780             step: usize,
781         ) -> impl FnMut() -> Option<I::Item> + '_ {
782             move || iter.nth_back(step)
783         }
784
785         match self.next_back() {
786             None => Try::from_ok(init),
787             Some(x) => {
788                 let acc = f(init, x)?;
789                 from_fn(nth_back(&mut self.iter, self.step)).try_fold(acc, f)
790             }
791         }
792     }
793
794     #[inline]
795     fn rfold<Acc, F>(mut self, init: Acc, mut f: F) -> Acc
796     where
797         Self: Sized,
798         F: FnMut(Acc, Self::Item) -> Acc,
799     {
800         #[inline]
801         fn nth_back<I: DoubleEndedIterator>(
802             iter: &mut I,
803             step: usize,
804         ) -> impl FnMut() -> Option<I::Item> + '_ {
805             move || iter.nth_back(step)
806         }
807
808         match self.next_back() {
809             None => init,
810             Some(x) => {
811                 let acc = f(init, x);
812                 from_fn(nth_back(&mut self.iter, self.step)).fold(acc, f)
813             }
814         }
815     }
816 }
817
818 // StepBy can only make the iterator shorter, so the len will still fit.
819 #[stable(feature = "iterator_step_by", since = "1.28.0")]
820 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
821
822 /// An iterator that maps the values of `iter` with `f`.
823 ///
824 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
825 /// documentation for more.
826 ///
827 /// [`map`]: trait.Iterator.html#method.map
828 /// [`Iterator`]: trait.Iterator.html
829 ///
830 /// # Notes about side effects
831 ///
832 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
833 /// you can also [`map`] backwards:
834 ///
835 /// ```rust
836 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
837 ///
838 /// assert_eq!(v, [4, 3, 2]);
839 /// ```
840 ///
841 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
842 ///
843 /// But if your closure has state, iterating backwards may act in a way you do
844 /// not expect. Let's go through an example. First, in the forward direction:
845 ///
846 /// ```rust
847 /// let mut c = 0;
848 ///
849 /// for pair in vec!['a', 'b', 'c'].into_iter()
850 ///                                .map(|letter| { c += 1; (letter, c) }) {
851 ///     println!("{:?}", pair);
852 /// }
853 /// ```
854 ///
855 /// This will print "('a', 1), ('b', 2), ('c', 3)".
856 ///
857 /// Now consider this twist where we add a call to `rev`. This version will
858 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
859 /// but the values of the counter still go in order. This is because `map()` is
860 /// still being called lazily on each item, but we are popping items off the
861 /// back of the vector now, instead of shifting them from the front.
862 ///
863 /// ```rust
864 /// let mut c = 0;
865 ///
866 /// for pair in vec!['a', 'b', 'c'].into_iter()
867 ///                                .map(|letter| { c += 1; (letter, c) })
868 ///                                .rev() {
869 ///     println!("{:?}", pair);
870 /// }
871 /// ```
872 #[must_use = "iterators are lazy and do nothing unless consumed"]
873 #[stable(feature = "rust1", since = "1.0.0")]
874 #[derive(Clone)]
875 pub struct Map<I, F> {
876     iter: I,
877     f: F,
878 }
879 impl<I, F> Map<I, F> {
880     pub(super) fn new(iter: I, f: F) -> Map<I, F> {
881         Map { iter, f }
882     }
883 }
884
885 #[stable(feature = "core_impl_debug", since = "1.9.0")]
886 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
887     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888         f.debug_struct("Map").field("iter", &self.iter).finish()
889     }
890 }
891
892 fn map_fold<T, B, Acc>(
893     mut f: impl FnMut(T) -> B,
894     mut g: impl FnMut(Acc, B) -> Acc,
895 ) -> impl FnMut(Acc, T) -> Acc {
896     move |acc, elt| g(acc, f(elt))
897 }
898
899 fn map_try_fold<'a, T, B, Acc, R>(
900     f: &'a mut impl FnMut(T) -> B,
901     mut g: impl FnMut(Acc, B) -> R + 'a,
902 ) -> impl FnMut(Acc, T) -> R + 'a {
903     move |acc, elt| g(acc, f(elt))
904 }
905
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl<B, I: Iterator, F> Iterator for Map<I, F>
908 where
909     F: FnMut(I::Item) -> B,
910 {
911     type Item = B;
912
913     #[inline]
914     fn next(&mut self) -> Option<B> {
915         self.iter.next().map(&mut self.f)
916     }
917
918     #[inline]
919     fn size_hint(&self) -> (usize, Option<usize>) {
920         self.iter.size_hint()
921     }
922
923     fn try_fold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
924     where
925         Self: Sized,
926         G: FnMut(Acc, Self::Item) -> R,
927         R: Try<Ok = Acc>,
928     {
929         self.iter.try_fold(init, map_try_fold(&mut self.f, g))
930     }
931
932     fn fold<Acc, G>(self, init: Acc, g: G) -> Acc
933     where
934         G: FnMut(Acc, Self::Item) -> Acc,
935     {
936         self.iter.fold(init, map_fold(self.f, g))
937     }
938
939     unsafe fn get_unchecked(&mut self, idx: usize) -> B
940     where
941         Self: TrustedRandomAccess,
942     {
943         // SAFETY: the caller must uphold the contract for
944         // `Iterator::get_unchecked`.
945         unsafe { (self.f)(try_get_unchecked(&mut self.iter, idx)) }
946     }
947 }
948
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F>
951 where
952     F: FnMut(I::Item) -> B,
953 {
954     #[inline]
955     fn next_back(&mut self) -> Option<B> {
956         self.iter.next_back().map(&mut self.f)
957     }
958
959     fn try_rfold<Acc, G, R>(&mut self, init: Acc, g: G) -> R
960     where
961         Self: Sized,
962         G: FnMut(Acc, Self::Item) -> R,
963         R: Try<Ok = Acc>,
964     {
965         self.iter.try_rfold(init, map_try_fold(&mut self.f, g))
966     }
967
968     fn rfold<Acc, G>(self, init: Acc, g: G) -> Acc
969     where
970         G: FnMut(Acc, Self::Item) -> Acc,
971     {
972         self.iter.rfold(init, map_fold(self.f, g))
973     }
974 }
975
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
978 where
979     F: FnMut(I::Item) -> B,
980 {
981     fn len(&self) -> usize {
982         self.iter.len()
983     }
984
985     fn is_empty(&self) -> bool {
986         self.iter.is_empty()
987     }
988 }
989
990 #[stable(feature = "fused", since = "1.26.0")]
991 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F> where F: FnMut(I::Item) -> B {}
992
993 #[unstable(feature = "trusted_len", issue = "37572")]
994 unsafe impl<B, I, F> TrustedLen for Map<I, F>
995 where
996     I: TrustedLen,
997     F: FnMut(I::Item) -> B,
998 {
999 }
1000
1001 #[doc(hidden)]
1002 #[unstable(feature = "trusted_random_access", issue = "none")]
1003 unsafe impl<I, F> TrustedRandomAccess for Map<I, F>
1004 where
1005     I: TrustedRandomAccess,
1006 {
1007     #[inline]
1008     fn may_have_side_effect() -> bool {
1009         true
1010     }
1011 }
1012
1013 #[unstable(issue = "0", feature = "inplace_iteration")]
1014 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for Map<I, F>
1015 where
1016     F: FnMut(I::Item) -> B,
1017     I: SourceIter<Source = S>,
1018 {
1019     type Source = S;
1020
1021     #[inline]
1022     unsafe fn as_inner(&mut self) -> &mut S {
1023         // Safety: unsafe function forwarding to unsafe function with the same requirements
1024         unsafe { SourceIter::as_inner(&mut self.iter) }
1025     }
1026 }
1027
1028 #[unstable(issue = "0", feature = "inplace_iteration")]
1029 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for Map<I, F> where F: FnMut(I::Item) -> B {}
1030
1031 /// An iterator that filters the elements of `iter` with `predicate`.
1032 ///
1033 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1034 /// documentation for more.
1035 ///
1036 /// [`filter`]: trait.Iterator.html#method.filter
1037 /// [`Iterator`]: trait.Iterator.html
1038 #[must_use = "iterators are lazy and do nothing unless consumed"]
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 #[derive(Clone)]
1041 pub struct Filter<I, P> {
1042     iter: I,
1043     predicate: P,
1044 }
1045 impl<I, P> Filter<I, P> {
1046     pub(super) fn new(iter: I, predicate: P) -> Filter<I, P> {
1047         Filter { iter, predicate }
1048     }
1049 }
1050
1051 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1052 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1053     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1054         f.debug_struct("Filter").field("iter", &self.iter).finish()
1055     }
1056 }
1057
1058 fn filter_fold<T, Acc>(
1059     mut predicate: impl FnMut(&T) -> bool,
1060     mut fold: impl FnMut(Acc, T) -> Acc,
1061 ) -> impl FnMut(Acc, T) -> Acc {
1062     move |acc, item| if predicate(&item) { fold(acc, item) } else { acc }
1063 }
1064
1065 fn filter_try_fold<'a, T, Acc, R: Try<Ok = Acc>>(
1066     predicate: &'a mut impl FnMut(&T) -> bool,
1067     mut fold: impl FnMut(Acc, T) -> R + 'a,
1068 ) -> impl FnMut(Acc, T) -> R + 'a {
1069     move |acc, item| if predicate(&item) { fold(acc, item) } else { R::from_ok(acc) }
1070 }
1071
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<I: Iterator, P> Iterator for Filter<I, P>
1074 where
1075     P: FnMut(&I::Item) -> bool,
1076 {
1077     type Item = I::Item;
1078
1079     #[inline]
1080     fn next(&mut self) -> Option<I::Item> {
1081         self.iter.find(&mut self.predicate)
1082     }
1083
1084     #[inline]
1085     fn size_hint(&self) -> (usize, Option<usize>) {
1086         let (_, upper) = self.iter.size_hint();
1087         (0, upper) // can't know a lower bound, due to the predicate
1088     }
1089
1090     // this special case allows the compiler to make `.filter(_).count()`
1091     // branchless. Barring perfect branch prediction (which is unattainable in
1092     // the general case), this will be much faster in >90% of cases (containing
1093     // virtually all real workloads) and only a tiny bit slower in the rest.
1094     //
1095     // Having this specialization thus allows us to write `.filter(p).count()`
1096     // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1097     // less readable and also less backwards-compatible to Rust before 1.10.
1098     //
1099     // Using the branchless version will also simplify the LLVM byte code, thus
1100     // leaving more budget for LLVM optimizations.
1101     #[inline]
1102     fn count(self) -> usize {
1103         #[inline]
1104         fn to_usize<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(T) -> usize {
1105             move |x| predicate(&x) as usize
1106         }
1107
1108         self.iter.map(to_usize(self.predicate)).sum()
1109     }
1110
1111     #[inline]
1112     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1113     where
1114         Self: Sized,
1115         Fold: FnMut(Acc, Self::Item) -> R,
1116         R: Try<Ok = Acc>,
1117     {
1118         self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold))
1119     }
1120
1121     #[inline]
1122     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1123     where
1124         Fold: FnMut(Acc, Self::Item) -> Acc,
1125     {
1126         self.iter.fold(init, filter_fold(self.predicate, fold))
1127     }
1128 }
1129
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1132 where
1133     P: FnMut(&I::Item) -> bool,
1134 {
1135     #[inline]
1136     fn next_back(&mut self) -> Option<I::Item> {
1137         self.iter.rfind(&mut self.predicate)
1138     }
1139
1140     #[inline]
1141     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1142     where
1143         Self: Sized,
1144         Fold: FnMut(Acc, Self::Item) -> R,
1145         R: Try<Ok = Acc>,
1146     {
1147         self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold))
1148     }
1149
1150     #[inline]
1151     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1152     where
1153         Fold: FnMut(Acc, Self::Item) -> Acc,
1154     {
1155         self.iter.rfold(init, filter_fold(self.predicate, fold))
1156     }
1157 }
1158
1159 #[stable(feature = "fused", since = "1.26.0")]
1160 impl<I: FusedIterator, P> FusedIterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {}
1161
1162 #[unstable(issue = "0", feature = "inplace_iteration")]
1163 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for Filter<I, P> where
1164     P: FnMut(&I::Item) -> bool,
1165     I: SourceIter<Source = S>
1166 {
1167     type Source = S;
1168
1169     #[inline]
1170     unsafe fn as_inner(&mut self) -> &mut S {
1171         // Safety: unsafe function forwarding to unsafe function with the same requirements
1172         unsafe { SourceIter::as_inner(&mut self.iter) }
1173     }
1174 }
1175
1176 #[unstable(issue = "0", feature = "inplace_iteration")]
1177 unsafe impl<I: InPlaceIterable, P> InPlaceIterable for Filter<I, P>
1178     where P: FnMut(&I::Item) -> bool {}
1179
1180 /// An iterator that uses `f` to both filter and map elements from `iter`.
1181 ///
1182 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1183 /// documentation for more.
1184 ///
1185 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1186 /// [`Iterator`]: trait.Iterator.html
1187 #[must_use = "iterators are lazy and do nothing unless consumed"]
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 #[derive(Clone)]
1190 pub struct FilterMap<I, F> {
1191     iter: I,
1192     f: F,
1193 }
1194 impl<I, F> FilterMap<I, F> {
1195     pub(super) fn new(iter: I, f: F) -> FilterMap<I, F> {
1196         FilterMap { iter, f }
1197     }
1198 }
1199
1200 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1201 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1202     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1203         f.debug_struct("FilterMap").field("iter", &self.iter).finish()
1204     }
1205 }
1206
1207 fn filter_map_fold<T, B, Acc>(
1208     mut f: impl FnMut(T) -> Option<B>,
1209     mut fold: impl FnMut(Acc, B) -> Acc,
1210 ) -> impl FnMut(Acc, T) -> Acc {
1211     move |acc, item| match f(item) {
1212         Some(x) => fold(acc, x),
1213         None => acc,
1214     }
1215 }
1216
1217 fn filter_map_try_fold<'a, T, B, Acc, R: Try<Ok = Acc>>(
1218     f: &'a mut impl FnMut(T) -> Option<B>,
1219     mut fold: impl FnMut(Acc, B) -> R + 'a,
1220 ) -> impl FnMut(Acc, T) -> R + 'a {
1221     move |acc, item| match f(item) {
1222         Some(x) => fold(acc, x),
1223         None => R::from_ok(acc),
1224     }
1225 }
1226
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1229 where
1230     F: FnMut(I::Item) -> Option<B>,
1231 {
1232     type Item = B;
1233
1234     #[inline]
1235     fn next(&mut self) -> Option<B> {
1236         self.iter.find_map(&mut self.f)
1237     }
1238
1239     #[inline]
1240     fn size_hint(&self) -> (usize, Option<usize>) {
1241         let (_, upper) = self.iter.size_hint();
1242         (0, upper) // can't know a lower bound, due to the predicate
1243     }
1244
1245     #[inline]
1246     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1247     where
1248         Self: Sized,
1249         Fold: FnMut(Acc, Self::Item) -> R,
1250         R: Try<Ok = Acc>,
1251     {
1252         self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold))
1253     }
1254
1255     #[inline]
1256     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1257     where
1258         Fold: FnMut(Acc, Self::Item) -> Acc,
1259     {
1260         self.iter.fold(init, filter_map_fold(self.f, fold))
1261     }
1262 }
1263
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1266 where
1267     F: FnMut(I::Item) -> Option<B>,
1268 {
1269     #[inline]
1270     fn next_back(&mut self) -> Option<B> {
1271         #[inline]
1272         fn find<T, B>(
1273             f: &mut impl FnMut(T) -> Option<B>,
1274         ) -> impl FnMut((), T) -> ControlFlow<(), B> + '_ {
1275             move |(), x| match f(x) {
1276                 Some(x) => ControlFlow::Break(x),
1277                 None => ControlFlow::Continue(()),
1278             }
1279         }
1280
1281         self.iter.try_rfold((), find(&mut self.f)).break_value()
1282     }
1283
1284     #[inline]
1285     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1286     where
1287         Self: Sized,
1288         Fold: FnMut(Acc, Self::Item) -> R,
1289         R: Try<Ok = Acc>,
1290     {
1291         self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold))
1292     }
1293
1294     #[inline]
1295     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1296     where
1297         Fold: FnMut(Acc, Self::Item) -> Acc,
1298     {
1299         self.iter.rfold(init, filter_map_fold(self.f, fold))
1300     }
1301 }
1302
1303 #[stable(feature = "fused", since = "1.26.0")]
1304 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F> where F: FnMut(I::Item) -> Option<B> {}
1305
1306 #[unstable(issue = "0", feature = "inplace_iteration")]
1307 unsafe impl<S: Iterator, B, I: Iterator, F> SourceIter for FilterMap<I, F> where
1308     F: FnMut(I::Item) -> Option<B>,
1309     I: SourceIter<Source = S>
1310 {
1311     type Source = S;
1312
1313     #[inline]
1314     unsafe fn as_inner(&mut self) -> &mut S {
1315         // Safety: unsafe function forwarding to unsafe function with the same requirements
1316         unsafe { SourceIter::as_inner(&mut self.iter) }
1317     }
1318 }
1319
1320 #[unstable(issue = "0", feature = "inplace_iteration")]
1321 unsafe impl<B, I: InPlaceIterable, F> InPlaceIterable for FilterMap<I, F>
1322     where F: FnMut(I::Item) -> Option<B> {}
1323
1324
1325 /// An iterator that yields the current count and the element during iteration.
1326 ///
1327 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1328 /// documentation for more.
1329 ///
1330 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1331 /// [`Iterator`]: trait.Iterator.html
1332 #[derive(Clone, Debug)]
1333 #[must_use = "iterators are lazy and do nothing unless consumed"]
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 pub struct Enumerate<I> {
1336     iter: I,
1337     count: usize,
1338 }
1339 impl<I> Enumerate<I> {
1340     pub(super) fn new(iter: I) -> Enumerate<I> {
1341         Enumerate { iter, count: 0 }
1342     }
1343 }
1344
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<I> Iterator for Enumerate<I>
1347 where
1348     I: Iterator,
1349 {
1350     type Item = (usize, <I as Iterator>::Item);
1351
1352     /// # Overflow Behavior
1353     ///
1354     /// The method does no guarding against overflows, so enumerating more than
1355     /// `usize::MAX` elements either produces the wrong result or panics. If
1356     /// debug assertions are enabled, a panic is guaranteed.
1357     ///
1358     /// # Panics
1359     ///
1360     /// Might panic if the index of the element overflows a `usize`.
1361     #[inline]
1362     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1363         let a = self.iter.next()?;
1364         let i = self.count;
1365         // Possible undefined overflow.
1366         AddAssign::add_assign(&mut self.count, 1);
1367         Some((i, a))
1368     }
1369
1370     #[inline]
1371     fn size_hint(&self) -> (usize, Option<usize>) {
1372         self.iter.size_hint()
1373     }
1374
1375     #[inline]
1376     fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1377         let a = self.iter.nth(n)?;
1378         // Possible undefined overflow.
1379         let i = Add::add(self.count, n);
1380         self.count = Add::add(i, 1);
1381         Some((i, a))
1382     }
1383
1384     #[inline]
1385     fn count(self) -> usize {
1386         self.iter.count()
1387     }
1388
1389     #[inline]
1390     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1391     where
1392         Self: Sized,
1393         Fold: FnMut(Acc, Self::Item) -> R,
1394         R: Try<Ok = Acc>,
1395     {
1396         #[inline]
1397         fn enumerate<'a, T, Acc, R>(
1398             count: &'a mut usize,
1399             mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a,
1400         ) -> impl FnMut(Acc, T) -> R + 'a {
1401             move |acc, item| {
1402                 let acc = fold(acc, (*count, item));
1403                 // Possible undefined overflow.
1404                 AddAssign::add_assign(count, 1);
1405                 acc
1406             }
1407         }
1408
1409         self.iter.try_fold(init, enumerate(&mut self.count, fold))
1410     }
1411
1412     #[inline]
1413     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1414     where
1415         Fold: FnMut(Acc, Self::Item) -> Acc,
1416     {
1417         #[inline]
1418         fn enumerate<T, Acc>(
1419             mut count: usize,
1420             mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1421         ) -> impl FnMut(Acc, T) -> Acc {
1422             move |acc, item| {
1423                 let acc = fold(acc, (count, item));
1424                 // Possible undefined overflow.
1425                 AddAssign::add_assign(&mut count, 1);
1426                 acc
1427             }
1428         }
1429
1430         self.iter.fold(init, enumerate(self.count, fold))
1431     }
1432
1433     unsafe fn get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item
1434     where
1435         Self: TrustedRandomAccess,
1436     {
1437         // SAFETY: the caller must uphold the contract for
1438         // `Iterator::get_unchecked`.
1439         let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
1440         (Add::add(self.count, idx), value)
1441     }
1442 }
1443
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<I> DoubleEndedIterator for Enumerate<I>
1446 where
1447     I: ExactSizeIterator + DoubleEndedIterator,
1448 {
1449     #[inline]
1450     fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1451         let a = self.iter.next_back()?;
1452         let len = self.iter.len();
1453         // Can safely add, `ExactSizeIterator` promises that the number of
1454         // elements fits into a `usize`.
1455         Some((self.count + len, a))
1456     }
1457
1458     #[inline]
1459     fn nth_back(&mut self, n: usize) -> Option<(usize, <I as Iterator>::Item)> {
1460         let a = self.iter.nth_back(n)?;
1461         let len = self.iter.len();
1462         // Can safely add, `ExactSizeIterator` promises that the number of
1463         // elements fits into a `usize`.
1464         Some((self.count + len, a))
1465     }
1466
1467     #[inline]
1468     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
1469     where
1470         Self: Sized,
1471         Fold: FnMut(Acc, Self::Item) -> R,
1472         R: Try<Ok = Acc>,
1473     {
1474         // Can safely add and subtract the count, as `ExactSizeIterator` promises
1475         // that the number of elements fits into a `usize`.
1476         fn enumerate<T, Acc, R>(
1477             mut count: usize,
1478             mut fold: impl FnMut(Acc, (usize, T)) -> R,
1479         ) -> impl FnMut(Acc, T) -> R {
1480             move |acc, item| {
1481                 count -= 1;
1482                 fold(acc, (count, item))
1483             }
1484         }
1485
1486         let count = self.count + self.iter.len();
1487         self.iter.try_rfold(init, enumerate(count, fold))
1488     }
1489
1490     #[inline]
1491     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1492     where
1493         Fold: FnMut(Acc, Self::Item) -> Acc,
1494     {
1495         // Can safely add and subtract the count, as `ExactSizeIterator` promises
1496         // that the number of elements fits into a `usize`.
1497         fn enumerate<T, Acc>(
1498             mut count: usize,
1499             mut fold: impl FnMut(Acc, (usize, T)) -> Acc,
1500         ) -> impl FnMut(Acc, T) -> Acc {
1501             move |acc, item| {
1502                 count -= 1;
1503                 fold(acc, (count, item))
1504             }
1505         }
1506
1507         let count = self.count + self.iter.len();
1508         self.iter.rfold(init, enumerate(count, fold))
1509     }
1510 }
1511
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<I> ExactSizeIterator for Enumerate<I>
1514 where
1515     I: ExactSizeIterator,
1516 {
1517     fn len(&self) -> usize {
1518         self.iter.len()
1519     }
1520
1521     fn is_empty(&self) -> bool {
1522         self.iter.is_empty()
1523     }
1524 }
1525
1526 #[doc(hidden)]
1527 #[unstable(feature = "trusted_random_access", issue = "none")]
1528 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1529 where
1530     I: TrustedRandomAccess,
1531 {
1532     fn may_have_side_effect() -> bool {
1533         I::may_have_side_effect()
1534     }
1535 }
1536
1537 #[stable(feature = "fused", since = "1.26.0")]
1538 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1539
1540 #[unstable(feature = "trusted_len", issue = "37572")]
1541 unsafe impl<I> TrustedLen for Enumerate<I> where I: TrustedLen {}
1542
1543 #[unstable(issue = "0", feature = "inplace_iteration")]
1544 unsafe impl<S: Iterator, I: Iterator> SourceIter for Enumerate<I>
1545 where
1546     I: SourceIter<Source = S>,
1547 {
1548     type Source = S;
1549
1550     #[inline]
1551     unsafe fn as_inner(&mut self) -> &mut S {
1552         // Safety: unsafe function forwarding to unsafe function with the same requirements
1553         unsafe { SourceIter::as_inner(&mut self.iter) }
1554     }
1555 }
1556
1557 #[unstable(issue = "0", feature = "inplace_iteration")]
1558 unsafe impl<I: InPlaceIterable> InPlaceIterable for Enumerate<I> {}
1559
1560 /// An iterator with a `peek()` that returns an optional reference to the next
1561 /// element.
1562 ///
1563 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1564 /// documentation for more.
1565 ///
1566 /// [`peekable`]: trait.Iterator.html#method.peekable
1567 /// [`Iterator`]: trait.Iterator.html
1568 #[derive(Clone, Debug)]
1569 #[must_use = "iterators are lazy and do nothing unless consumed"]
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 pub struct Peekable<I: Iterator> {
1572     iter: I,
1573     /// Remember a peeked value, even if it was None.
1574     peeked: Option<Option<I::Item>>,
1575 }
1576 impl<I: Iterator> Peekable<I> {
1577     pub(super) fn new(iter: I) -> Peekable<I> {
1578         Peekable { iter, peeked: None }
1579     }
1580 }
1581
1582 // Peekable must remember if a None has been seen in the `.peek()` method.
1583 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1584 // underlying iterator at most once. This does not by itself make the iterator
1585 // fused.
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl<I: Iterator> Iterator for Peekable<I> {
1588     type Item = I::Item;
1589
1590     #[inline]
1591     fn next(&mut self) -> Option<I::Item> {
1592         match self.peeked.take() {
1593             Some(v) => v,
1594             None => self.iter.next(),
1595         }
1596     }
1597
1598     #[inline]
1599     #[rustc_inherit_overflow_checks]
1600     fn count(mut self) -> usize {
1601         match self.peeked.take() {
1602             Some(None) => 0,
1603             Some(Some(_)) => 1 + self.iter.count(),
1604             None => self.iter.count(),
1605         }
1606     }
1607
1608     #[inline]
1609     fn nth(&mut self, n: usize) -> Option<I::Item> {
1610         match self.peeked.take() {
1611             Some(None) => None,
1612             Some(v @ Some(_)) if n == 0 => v,
1613             Some(Some(_)) => self.iter.nth(n - 1),
1614             None => self.iter.nth(n),
1615         }
1616     }
1617
1618     #[inline]
1619     fn last(mut self) -> Option<I::Item> {
1620         let peek_opt = match self.peeked.take() {
1621             Some(None) => return None,
1622             Some(v) => v,
1623             None => None,
1624         };
1625         self.iter.last().or(peek_opt)
1626     }
1627
1628     #[inline]
1629     fn size_hint(&self) -> (usize, Option<usize>) {
1630         let peek_len = match self.peeked {
1631             Some(None) => return (0, Some(0)),
1632             Some(Some(_)) => 1,
1633             None => 0,
1634         };
1635         let (lo, hi) = self.iter.size_hint();
1636         let lo = lo.saturating_add(peek_len);
1637         let hi = match hi {
1638             Some(x) => x.checked_add(peek_len),
1639             None => None,
1640         };
1641         (lo, hi)
1642     }
1643
1644     #[inline]
1645     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1646     where
1647         Self: Sized,
1648         F: FnMut(B, Self::Item) -> R,
1649         R: Try<Ok = B>,
1650     {
1651         let acc = match self.peeked.take() {
1652             Some(None) => return Try::from_ok(init),
1653             Some(Some(v)) => f(init, v)?,
1654             None => init,
1655         };
1656         self.iter.try_fold(acc, f)
1657     }
1658
1659     #[inline]
1660     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1661     where
1662         Fold: FnMut(Acc, Self::Item) -> Acc,
1663     {
1664         let acc = match self.peeked {
1665             Some(None) => return init,
1666             Some(Some(v)) => fold(init, v),
1667             None => init,
1668         };
1669         self.iter.fold(acc, fold)
1670     }
1671 }
1672
1673 #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
1674 impl<I> DoubleEndedIterator for Peekable<I>
1675 where
1676     I: DoubleEndedIterator,
1677 {
1678     #[inline]
1679     fn next_back(&mut self) -> Option<Self::Item> {
1680         match self.peeked.as_mut() {
1681             Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
1682             Some(None) => None,
1683             None => self.iter.next_back(),
1684         }
1685     }
1686
1687     #[inline]
1688     fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
1689     where
1690         Self: Sized,
1691         F: FnMut(B, Self::Item) -> R,
1692         R: Try<Ok = B>,
1693     {
1694         match self.peeked.take() {
1695             Some(None) => Try::from_ok(init),
1696             Some(Some(v)) => match self.iter.try_rfold(init, &mut f).into_result() {
1697                 Ok(acc) => f(acc, v),
1698                 Err(e) => {
1699                     self.peeked = Some(Some(v));
1700                     Try::from_error(e)
1701                 }
1702             },
1703             None => self.iter.try_rfold(init, f),
1704         }
1705     }
1706
1707     #[inline]
1708     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1709     where
1710         Fold: FnMut(Acc, Self::Item) -> Acc,
1711     {
1712         match self.peeked {
1713             Some(None) => init,
1714             Some(Some(v)) => {
1715                 let acc = self.iter.rfold(init, &mut fold);
1716                 fold(acc, v)
1717             }
1718             None => self.iter.rfold(init, fold),
1719         }
1720     }
1721 }
1722
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1725
1726 #[stable(feature = "fused", since = "1.26.0")]
1727 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1728
1729 impl<I: Iterator> Peekable<I> {
1730     /// Returns a reference to the next() value without advancing the iterator.
1731     ///
1732     /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1733     /// But if the iteration is over, `None` is returned.
1734     ///
1735     /// [`next`]: trait.Iterator.html#tymethod.next
1736     ///
1737     /// Because `peek()` returns a reference, and many iterators iterate over
1738     /// references, there can be a possibly confusing situation where the
1739     /// return value is a double reference. You can see this effect in the
1740     /// examples below.
1741     ///
1742     /// # Examples
1743     ///
1744     /// Basic usage:
1745     ///
1746     /// ```
1747     /// let xs = [1, 2, 3];
1748     ///
1749     /// let mut iter = xs.iter().peekable();
1750     ///
1751     /// // peek() lets us see into the future
1752     /// assert_eq!(iter.peek(), Some(&&1));
1753     /// assert_eq!(iter.next(), Some(&1));
1754     ///
1755     /// assert_eq!(iter.next(), Some(&2));
1756     ///
1757     /// // The iterator does not advance even if we `peek` multiple times
1758     /// assert_eq!(iter.peek(), Some(&&3));
1759     /// assert_eq!(iter.peek(), Some(&&3));
1760     ///
1761     /// assert_eq!(iter.next(), Some(&3));
1762     ///
1763     /// // After the iterator is finished, so is `peek()`
1764     /// assert_eq!(iter.peek(), None);
1765     /// assert_eq!(iter.next(), None);
1766     /// ```
1767     #[inline]
1768     #[stable(feature = "rust1", since = "1.0.0")]
1769     pub fn peek(&mut self) -> Option<&I::Item> {
1770         let iter = &mut self.iter;
1771         self.peeked.get_or_insert_with(|| iter.next()).as_ref()
1772     }
1773
1774     /// Consume the next value of this iterator if a condition is true.
1775     ///
1776     /// If `func` returns `true` for the next value of this iterator, consume and return it.
1777     /// Otherwise, return `None`.
1778     ///
1779     /// # Examples
1780     /// Consume a number if it's equal to 0.
1781     /// ```
1782     /// #![feature(peekable_next_if)]
1783     /// let mut iter = (0..5).peekable();
1784     /// // The first item of the iterator is 0; consume it.
1785     /// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
1786     /// // The next item returned is now 1, so `consume` will return `false`.
1787     /// assert_eq!(iter.next_if(|&x| x == 0), None);
1788     /// // `next_if` saves the value of the next item if it was not equal to `expected`.
1789     /// assert_eq!(iter.next(), Some(1));
1790     /// ```
1791     ///
1792     /// Consume any number less than 10.
1793     /// ```
1794     /// #![feature(peekable_next_if)]
1795     /// let mut iter = (1..20).peekable();
1796     /// // Consume all numbers less than 10
1797     /// while iter.next_if(|&x| x < 10).is_some() {}
1798     /// // The next value returned will be 10
1799     /// assert_eq!(iter.next(), Some(10));
1800     /// ```
1801     #[unstable(feature = "peekable_next_if", issue = "72480")]
1802     pub fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item> {
1803         match self.next() {
1804             Some(matched) if func(&matched) => Some(matched),
1805             other => {
1806                 // Since we called `self.next()`, we consumed `self.peeked`.
1807                 assert!(self.peeked.is_none());
1808                 self.peeked = Some(other);
1809                 None
1810             }
1811         }
1812     }
1813
1814     /// Consume the next item if it is equal to `expected`.
1815     ///
1816     /// # Example
1817     /// Consume a number if it's equal to 0.
1818     /// ```
1819     /// #![feature(peekable_next_if)]
1820     /// let mut iter = (0..5).peekable();
1821     /// // The first item of the iterator is 0; consume it.
1822     /// assert_eq!(iter.next_if_eq(&0), Some(0));
1823     /// // The next item returned is now 1, so `consume` will return `false`.
1824     /// assert_eq!(iter.next_if_eq(&0), None);
1825     /// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
1826     /// assert_eq!(iter.next(), Some(1));
1827     /// ```
1828     #[unstable(feature = "peekable_next_if", issue = "72480")]
1829     pub fn next_if_eq<R>(&mut self, expected: &R) -> Option<I::Item>
1830     where
1831         R: ?Sized,
1832         I::Item: PartialEq<R>,
1833     {
1834         self.next_if(|next| next == expected)
1835     }
1836 }
1837
1838 #[unstable(feature = "trusted_len", issue = "37572")]
1839 unsafe impl<I> TrustedLen for Peekable<I> where I: TrustedLen {}
1840
1841 #[unstable(issue = "0", feature = "inplace_iteration")]
1842 unsafe impl<S: Iterator, I: Iterator> SourceIter for Peekable<I>
1843 where
1844     I: SourceIter<Source = S>,
1845 {
1846     type Source = S;
1847
1848     #[inline]
1849     unsafe fn as_inner(&mut self) -> &mut S {
1850         // Safety: unsafe function forwarding to unsafe function with the same requirements
1851         unsafe { SourceIter::as_inner(&mut self.iter) }
1852     }
1853 }
1854
1855 #[unstable(issue = "0", feature = "inplace_iteration")]
1856 unsafe impl<I: InPlaceIterable> InPlaceIterable for Peekable<I> {}
1857
1858 /// An iterator that rejects elements while `predicate` returns `true`.
1859 ///
1860 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1861 /// documentation for more.
1862 ///
1863 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1864 /// [`Iterator`]: trait.Iterator.html
1865 #[must_use = "iterators are lazy and do nothing unless consumed"]
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 #[derive(Clone)]
1868 pub struct SkipWhile<I, P> {
1869     iter: I,
1870     flag: bool,
1871     predicate: P,
1872 }
1873 impl<I, P> SkipWhile<I, P> {
1874     pub(super) fn new(iter: I, predicate: P) -> SkipWhile<I, P> {
1875         SkipWhile { iter, flag: false, predicate }
1876     }
1877 }
1878
1879 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1880 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1881     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882         f.debug_struct("SkipWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
1883     }
1884 }
1885
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1888 where
1889     P: FnMut(&I::Item) -> bool,
1890 {
1891     type Item = I::Item;
1892
1893     #[inline]
1894     fn next(&mut self) -> Option<I::Item> {
1895         fn check<'a, T>(
1896             flag: &'a mut bool,
1897             pred: &'a mut impl FnMut(&T) -> bool,
1898         ) -> impl FnMut(&T) -> bool + 'a {
1899             move |x| {
1900                 if *flag || !pred(x) {
1901                     *flag = true;
1902                     true
1903                 } else {
1904                     false
1905                 }
1906             }
1907         }
1908
1909         let flag = &mut self.flag;
1910         let pred = &mut self.predicate;
1911         self.iter.find(check(flag, pred))
1912     }
1913
1914     #[inline]
1915     fn size_hint(&self) -> (usize, Option<usize>) {
1916         let (_, upper) = self.iter.size_hint();
1917         (0, upper) // can't know a lower bound, due to the predicate
1918     }
1919
1920     #[inline]
1921     fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R
1922     where
1923         Self: Sized,
1924         Fold: FnMut(Acc, Self::Item) -> R,
1925         R: Try<Ok = Acc>,
1926     {
1927         if !self.flag {
1928             match self.next() {
1929                 Some(v) => init = fold(init, v)?,
1930                 None => return Try::from_ok(init),
1931             }
1932         }
1933         self.iter.try_fold(init, fold)
1934     }
1935
1936     #[inline]
1937     fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
1938     where
1939         Fold: FnMut(Acc, Self::Item) -> Acc,
1940     {
1941         if !self.flag {
1942             match self.next() {
1943                 Some(v) => init = fold(init, v),
1944                 None => return init,
1945             }
1946         }
1947         self.iter.fold(init, fold)
1948     }
1949 }
1950
1951 #[stable(feature = "fused", since = "1.26.0")]
1952 impl<I, P> FusedIterator for SkipWhile<I, P>
1953 where
1954     I: FusedIterator,
1955     P: FnMut(&I::Item) -> bool,
1956 {
1957 }
1958
1959 #[unstable(issue = "0", feature = "inplace_iteration")]
1960 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for SkipWhile<I, P> where
1961     P: FnMut(&I::Item) -> bool,
1962     I: SourceIter<Source = S>
1963 {
1964     type Source = S;
1965
1966     #[inline]
1967     unsafe fn as_inner(&mut self) -> &mut S {
1968         // Safety: unsafe function forwarding to unsafe function with the same requirements
1969         unsafe { SourceIter::as_inner(&mut self.iter) }
1970     }
1971 }
1972
1973 #[unstable(issue = "0", feature = "inplace_iteration")]
1974 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for SkipWhile<I, F>
1975     where F: FnMut(&I::Item) -> bool {}
1976
1977 /// An iterator that only accepts elements while `predicate` returns `true`.
1978 ///
1979 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1980 /// documentation for more.
1981 ///
1982 /// [`take_while`]: trait.Iterator.html#method.take_while
1983 /// [`Iterator`]: trait.Iterator.html
1984 #[must_use = "iterators are lazy and do nothing unless consumed"]
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 #[derive(Clone)]
1987 pub struct TakeWhile<I, P> {
1988     iter: I,
1989     flag: bool,
1990     predicate: P,
1991 }
1992 impl<I, P> TakeWhile<I, P> {
1993     pub(super) fn new(iter: I, predicate: P) -> TakeWhile<I, P> {
1994         TakeWhile { iter, flag: false, predicate }
1995     }
1996 }
1997
1998 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1999 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
2000     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2001         f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish()
2002     }
2003 }
2004
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2007 where
2008     P: FnMut(&I::Item) -> bool,
2009 {
2010     type Item = I::Item;
2011
2012     #[inline]
2013     fn next(&mut self) -> Option<I::Item> {
2014         if self.flag {
2015             None
2016         } else {
2017             let x = self.iter.next()?;
2018             if (self.predicate)(&x) {
2019                 Some(x)
2020             } else {
2021                 self.flag = true;
2022                 None
2023             }
2024         }
2025     }
2026
2027     #[inline]
2028     fn size_hint(&self) -> (usize, Option<usize>) {
2029         if self.flag {
2030             (0, Some(0))
2031         } else {
2032             let (_, upper) = self.iter.size_hint();
2033             (0, upper) // can't know a lower bound, due to the predicate
2034         }
2035     }
2036
2037     #[inline]
2038     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2039     where
2040         Self: Sized,
2041         Fold: FnMut(Acc, Self::Item) -> R,
2042         R: Try<Ok = Acc>,
2043     {
2044         fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2045             flag: &'a mut bool,
2046             p: &'a mut impl FnMut(&T) -> bool,
2047             mut fold: impl FnMut(Acc, T) -> R + 'a,
2048         ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2049             move |acc, x| {
2050                 if p(&x) {
2051                     ControlFlow::from_try(fold(acc, x))
2052                 } else {
2053                     *flag = true;
2054                     ControlFlow::Break(Try::from_ok(acc))
2055                 }
2056             }
2057         }
2058
2059         if self.flag {
2060             Try::from_ok(init)
2061         } else {
2062             let flag = &mut self.flag;
2063             let p = &mut self.predicate;
2064             self.iter.try_fold(init, check(flag, p, fold)).into_try()
2065         }
2066     }
2067
2068     #[inline]
2069     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2070     where
2071         Self: Sized,
2072         Fold: FnMut(Acc, Self::Item) -> Acc,
2073     {
2074         #[inline]
2075         fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2076             move |acc, x| Ok(f(acc, x))
2077         }
2078
2079         self.try_fold(init, ok(fold)).unwrap()
2080     }
2081 }
2082
2083 #[stable(feature = "fused", since = "1.26.0")]
2084 impl<I, P> FusedIterator for TakeWhile<I, P>
2085 where
2086     I: FusedIterator,
2087     P: FnMut(&I::Item) -> bool,
2088 {
2089 }
2090
2091 /// An iterator that only accepts elements while `predicate` returns `Some(_)`.
2092 ///
2093 /// This `struct` is created by the [`map_while`] method on [`Iterator`]. See its
2094 /// documentation for more.
2095 ///
2096 /// [`map_while`]: trait.Iterator.html#method.map_while
2097 /// [`Iterator`]: trait.Iterator.html
2098 #[must_use = "iterators are lazy and do nothing unless consumed"]
2099 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2100 #[derive(Clone)]
2101 pub struct MapWhile<I, P> {
2102     iter: I,
2103     predicate: P,
2104 }
2105
2106 impl<I, P> MapWhile<I, P> {
2107     pub(super) fn new(iter: I, predicate: P) -> MapWhile<I, P> {
2108         MapWhile { iter, predicate }
2109     }
2110 }
2111
2112 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2113 impl<I: fmt::Debug, P> fmt::Debug for MapWhile<I, P> {
2114     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2115         f.debug_struct("MapWhile").field("iter", &self.iter).finish()
2116     }
2117 }
2118
2119 #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
2120 impl<B, I: Iterator, P> Iterator for MapWhile<I, P>
2121 where
2122     P: FnMut(I::Item) -> Option<B>,
2123 {
2124     type Item = B;
2125
2126     #[inline]
2127     fn next(&mut self) -> Option<B> {
2128         let x = self.iter.next()?;
2129         (self.predicate)(x)
2130     }
2131
2132     #[inline]
2133     fn size_hint(&self) -> (usize, Option<usize>) {
2134         let (_, upper) = self.iter.size_hint();
2135         (0, upper) // can't know a lower bound, due to the predicate
2136     }
2137
2138     #[inline]
2139     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R
2140     where
2141         Self: Sized,
2142         Fold: FnMut(Acc, Self::Item) -> R,
2143         R: Try<Ok = Acc>,
2144     {
2145         let Self { iter, predicate } = self;
2146         iter.try_fold(init, |acc, x| match predicate(x) {
2147             Some(item) => ControlFlow::from_try(fold(acc, item)),
2148             None => ControlFlow::Break(Try::from_ok(acc)),
2149         })
2150         .into_try()
2151     }
2152
2153     #[inline]
2154     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2155     where
2156         Self: Sized,
2157         Fold: FnMut(Acc, Self::Item) -> Acc,
2158     {
2159         #[inline]
2160         fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2161             move |acc, x| Ok(f(acc, x))
2162         }
2163
2164         self.try_fold(init, ok(fold)).unwrap()
2165     }
2166 }
2167
2168 #[unstable(issue = "0", feature = "inplace_iteration")]
2169 unsafe impl<S: Iterator, P, I: Iterator> SourceIter for TakeWhile<I, P> where
2170     P: FnMut(&I::Item) -> bool,
2171     I: SourceIter<Source = S>
2172 {
2173     type Source = S;
2174
2175     #[inline]
2176     unsafe fn as_inner(&mut self) -> &mut S {
2177         // Safety: unsafe function forwarding to unsafe function with the same requirements
2178         unsafe { SourceIter::as_inner(&mut self.iter) }
2179     }
2180 }
2181
2182 #[unstable(issue = "0", feature = "inplace_iteration")]
2183 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for TakeWhile<I, F>
2184     where F: FnMut(&I::Item) -> bool {}
2185
2186
2187 /// An iterator that skips over `n` elements of `iter`.
2188 ///
2189 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
2190 /// documentation for more.
2191 ///
2192 /// [`skip`]: trait.Iterator.html#method.skip
2193 /// [`Iterator`]: trait.Iterator.html
2194 #[derive(Clone, Debug)]
2195 #[must_use = "iterators are lazy and do nothing unless consumed"]
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 pub struct Skip<I> {
2198     iter: I,
2199     n: usize,
2200 }
2201 impl<I> Skip<I> {
2202     pub(super) fn new(iter: I, n: usize) -> Skip<I> {
2203         Skip { iter, n }
2204     }
2205 }
2206
2207 #[stable(feature = "rust1", since = "1.0.0")]
2208 impl<I> Iterator for Skip<I>
2209 where
2210     I: Iterator,
2211 {
2212     type Item = <I as Iterator>::Item;
2213
2214     #[inline]
2215     fn next(&mut self) -> Option<I::Item> {
2216         if self.n == 0 {
2217             self.iter.next()
2218         } else {
2219             let old_n = self.n;
2220             self.n = 0;
2221             self.iter.nth(old_n)
2222         }
2223     }
2224
2225     #[inline]
2226     fn nth(&mut self, n: usize) -> Option<I::Item> {
2227         // Can't just add n + self.n due to overflow.
2228         if self.n > 0 {
2229             let to_skip = self.n;
2230             self.n = 0;
2231             // nth(n) skips n+1
2232             self.iter.nth(to_skip - 1)?;
2233         }
2234         self.iter.nth(n)
2235     }
2236
2237     #[inline]
2238     fn count(mut self) -> usize {
2239         if self.n > 0 {
2240             // nth(n) skips n+1
2241             if self.iter.nth(self.n - 1).is_none() {
2242                 return 0;
2243             }
2244         }
2245         self.iter.count()
2246     }
2247
2248     #[inline]
2249     fn last(mut self) -> Option<I::Item> {
2250         if self.n > 0 {
2251             // nth(n) skips n+1
2252             self.iter.nth(self.n - 1)?;
2253         }
2254         self.iter.last()
2255     }
2256
2257     #[inline]
2258     fn size_hint(&self) -> (usize, Option<usize>) {
2259         let (lower, upper) = self.iter.size_hint();
2260
2261         let lower = lower.saturating_sub(self.n);
2262         let upper = match upper {
2263             Some(x) => Some(x.saturating_sub(self.n)),
2264             None => None,
2265         };
2266
2267         (lower, upper)
2268     }
2269
2270     #[inline]
2271     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2272     where
2273         Self: Sized,
2274         Fold: FnMut(Acc, Self::Item) -> R,
2275         R: Try<Ok = Acc>,
2276     {
2277         let n = self.n;
2278         self.n = 0;
2279         if n > 0 {
2280             // nth(n) skips n+1
2281             if self.iter.nth(n - 1).is_none() {
2282                 return Try::from_ok(init);
2283             }
2284         }
2285         self.iter.try_fold(init, fold)
2286     }
2287
2288     #[inline]
2289     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2290     where
2291         Fold: FnMut(Acc, Self::Item) -> Acc,
2292     {
2293         if self.n > 0 {
2294             // nth(n) skips n+1
2295             if self.iter.nth(self.n - 1).is_none() {
2296                 return init;
2297             }
2298         }
2299         self.iter.fold(init, fold)
2300     }
2301 }
2302
2303 #[stable(feature = "rust1", since = "1.0.0")]
2304 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2305
2306 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
2307 impl<I> DoubleEndedIterator for Skip<I>
2308 where
2309     I: DoubleEndedIterator + ExactSizeIterator,
2310 {
2311     fn next_back(&mut self) -> Option<Self::Item> {
2312         if self.len() > 0 { self.iter.next_back() } else { None }
2313     }
2314
2315     #[inline]
2316     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
2317         let len = self.len();
2318         if n < len {
2319             self.iter.nth_back(n)
2320         } else {
2321             if len > 0 {
2322                 // consume the original iterator
2323                 self.iter.nth_back(len - 1);
2324             }
2325             None
2326         }
2327     }
2328
2329     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2330     where
2331         Self: Sized,
2332         Fold: FnMut(Acc, Self::Item) -> R,
2333         R: Try<Ok = Acc>,
2334     {
2335         fn check<T, Acc, R: Try<Ok = Acc>>(
2336             mut n: usize,
2337             mut fold: impl FnMut(Acc, T) -> R,
2338         ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> {
2339             move |acc, x| {
2340                 n -= 1;
2341                 let r = fold(acc, x);
2342                 if n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2343             }
2344         }
2345
2346         let n = self.len();
2347         if n == 0 {
2348             Try::from_ok(init)
2349         } else {
2350             self.iter.try_rfold(init, check(n, fold)).into_try()
2351         }
2352     }
2353
2354     fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2355     where
2356         Fold: FnMut(Acc, Self::Item) -> Acc,
2357     {
2358         #[inline]
2359         fn ok<Acc, T>(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, T) -> Result<Acc, !> {
2360             move |acc, x| Ok(f(acc, x))
2361         }
2362
2363         self.try_rfold(init, ok(fold)).unwrap()
2364     }
2365 }
2366
2367 #[stable(feature = "fused", since = "1.26.0")]
2368 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2369
2370 #[unstable(issue = "0", feature = "inplace_iteration")]
2371 unsafe impl<S: Iterator, I: Iterator> SourceIter for Skip<I>
2372 where
2373     I: SourceIter<Source = S>,
2374 {
2375     type Source = S;
2376
2377     #[inline]
2378     unsafe fn as_inner(&mut self) -> &mut S {
2379         // Safety: unsafe function forwarding to unsafe function with the same requirements
2380         unsafe { SourceIter::as_inner(&mut self.iter) }
2381     }
2382 }
2383
2384 #[unstable(issue = "0", feature = "inplace_iteration")]
2385 unsafe impl<I: InPlaceIterable> InPlaceIterable for Skip<I> {}
2386
2387 /// An iterator that only iterates over the first `n` iterations of `iter`.
2388 ///
2389 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2390 /// documentation for more.
2391 ///
2392 /// [`take`]: trait.Iterator.html#method.take
2393 /// [`Iterator`]: trait.Iterator.html
2394 #[derive(Clone, Debug)]
2395 #[must_use = "iterators are lazy and do nothing unless consumed"]
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 pub struct Take<I> {
2398     pub(super) iter: I,
2399     pub(super) n: usize,
2400 }
2401 impl<I> Take<I> {
2402     pub(super) fn new(iter: I, n: usize) -> Take<I> {
2403         Take { iter, n }
2404     }
2405 }
2406
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<I> Iterator for Take<I>
2409 where
2410     I: Iterator,
2411 {
2412     type Item = <I as Iterator>::Item;
2413
2414     #[inline]
2415     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2416         if self.n != 0 {
2417             self.n -= 1;
2418             self.iter.next()
2419         } else {
2420             None
2421         }
2422     }
2423
2424     #[inline]
2425     fn nth(&mut self, n: usize) -> Option<I::Item> {
2426         if self.n > n {
2427             self.n -= n + 1;
2428             self.iter.nth(n)
2429         } else {
2430             if self.n > 0 {
2431                 self.iter.nth(self.n - 1);
2432                 self.n = 0;
2433             }
2434             None
2435         }
2436     }
2437
2438     #[inline]
2439     fn size_hint(&self) -> (usize, Option<usize>) {
2440         if self.n == 0 {
2441             return (0, Some(0));
2442         }
2443
2444         let (lower, upper) = self.iter.size_hint();
2445
2446         let lower = cmp::min(lower, self.n);
2447
2448         let upper = match upper {
2449             Some(x) if x < self.n => Some(x),
2450             _ => Some(self.n),
2451         };
2452
2453         (lower, upper)
2454     }
2455
2456     #[inline]
2457     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2458     where
2459         Self: Sized,
2460         Fold: FnMut(Acc, Self::Item) -> R,
2461         R: Try<Ok = Acc>,
2462     {
2463         fn check<'a, T, Acc, R: Try<Ok = Acc>>(
2464             n: &'a mut usize,
2465             mut fold: impl FnMut(Acc, T) -> R + 'a,
2466         ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2467             move |acc, x| {
2468                 *n -= 1;
2469                 let r = fold(acc, x);
2470                 if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) }
2471             }
2472         }
2473
2474         if self.n == 0 {
2475             Try::from_ok(init)
2476         } else {
2477             let n = &mut self.n;
2478             self.iter.try_fold(init, check(n, fold)).into_try()
2479         }
2480     }
2481
2482     #[inline]
2483     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2484     where
2485         Self: Sized,
2486         Fold: FnMut(Acc, Self::Item) -> Acc,
2487     {
2488         #[inline]
2489         fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2490             move |acc, x| Ok(f(acc, x))
2491         }
2492
2493         self.try_fold(init, ok(fold)).unwrap()
2494     }
2495 }
2496
2497 #[unstable(issue = "0", feature = "inplace_iteration")]
2498 unsafe impl<S: Iterator, I: Iterator> SourceIter for Take<I> where I: SourceIter<Source = S> {
2499     type Source = S;
2500
2501     #[inline]
2502     unsafe fn as_inner(&mut self) -> &mut S {
2503         // Safety: unsafe function forwarding to unsafe function with the same requirements
2504         unsafe { SourceIter::as_inner(&mut self.iter) }
2505     }
2506 }
2507
2508 #[unstable(issue = "0", feature = "inplace_iteration")]
2509 unsafe impl<I: InPlaceIterable> InPlaceIterable for Take<I> {}
2510
2511 #[stable(feature = "double_ended_take_iterator", since = "1.38.0")]
2512 impl<I> DoubleEndedIterator for Take<I>
2513 where
2514     I: DoubleEndedIterator + ExactSizeIterator,
2515 {
2516     #[inline]
2517     fn next_back(&mut self) -> Option<Self::Item> {
2518         if self.n == 0 {
2519             None
2520         } else {
2521             let n = self.n;
2522             self.n -= 1;
2523             self.iter.nth_back(self.iter.len().saturating_sub(n))
2524         }
2525     }
2526
2527     #[inline]
2528     fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
2529         let len = self.iter.len();
2530         if self.n > n {
2531             let m = len.saturating_sub(self.n) + n;
2532             self.n -= n + 1;
2533             self.iter.nth_back(m)
2534         } else {
2535             if len > 0 {
2536                 self.iter.nth_back(len - 1);
2537             }
2538             None
2539         }
2540     }
2541
2542     #[inline]
2543     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2544     where
2545         Self: Sized,
2546         Fold: FnMut(Acc, Self::Item) -> R,
2547         R: Try<Ok = Acc>,
2548     {
2549         if self.n == 0 {
2550             Try::from_ok(init)
2551         } else {
2552             let len = self.iter.len();
2553             if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2554                 Try::from_ok(init)
2555             } else {
2556                 self.iter.try_rfold(init, fold)
2557             }
2558         }
2559     }
2560
2561     #[inline]
2562     fn rfold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2563     where
2564         Self: Sized,
2565         Fold: FnMut(Acc, Self::Item) -> Acc,
2566     {
2567         if self.n == 0 {
2568             init
2569         } else {
2570             let len = self.iter.len();
2571             if len > self.n && self.iter.nth_back(len - self.n - 1).is_none() {
2572                 init
2573             } else {
2574                 self.iter.rfold(init, fold)
2575             }
2576         }
2577     }
2578 }
2579
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2582
2583 #[stable(feature = "fused", since = "1.26.0")]
2584 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2585
2586 #[unstable(feature = "trusted_len", issue = "37572")]
2587 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2588
2589 /// An iterator to maintain state while iterating another iterator.
2590 ///
2591 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2592 /// documentation for more.
2593 ///
2594 /// [`scan`]: trait.Iterator.html#method.scan
2595 /// [`Iterator`]: trait.Iterator.html
2596 #[must_use = "iterators are lazy and do nothing unless consumed"]
2597 #[stable(feature = "rust1", since = "1.0.0")]
2598 #[derive(Clone)]
2599 pub struct Scan<I, St, F> {
2600     iter: I,
2601     f: F,
2602     state: St,
2603 }
2604 impl<I, St, F> Scan<I, St, F> {
2605     pub(super) fn new(iter: I, state: St, f: F) -> Scan<I, St, F> {
2606         Scan { iter, state, f }
2607     }
2608 }
2609
2610 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2611 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2612     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2613         f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish()
2614     }
2615 }
2616
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 impl<B, I, St, F> Iterator for Scan<I, St, F>
2619 where
2620     I: Iterator,
2621     F: FnMut(&mut St, I::Item) -> Option<B>,
2622 {
2623     type Item = B;
2624
2625     #[inline]
2626     fn next(&mut self) -> Option<B> {
2627         let a = self.iter.next()?;
2628         (self.f)(&mut self.state, a)
2629     }
2630
2631     #[inline]
2632     fn size_hint(&self) -> (usize, Option<usize>) {
2633         let (_, upper) = self.iter.size_hint();
2634         (0, upper) // can't know a lower bound, due to the scan function
2635     }
2636
2637     #[inline]
2638     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2639     where
2640         Self: Sized,
2641         Fold: FnMut(Acc, Self::Item) -> R,
2642         R: Try<Ok = Acc>,
2643     {
2644         fn scan<'a, T, St, B, Acc, R: Try<Ok = Acc>>(
2645             state: &'a mut St,
2646             f: &'a mut impl FnMut(&mut St, T) -> Option<B>,
2647             mut fold: impl FnMut(Acc, B) -> R + 'a,
2648         ) -> impl FnMut(Acc, T) -> ControlFlow<Acc, R> + 'a {
2649             move |acc, x| match f(state, x) {
2650                 None => ControlFlow::Break(Try::from_ok(acc)),
2651                 Some(x) => ControlFlow::from_try(fold(acc, x)),
2652             }
2653         }
2654
2655         let state = &mut self.state;
2656         let f = &mut self.f;
2657         self.iter.try_fold(init, scan(state, f, fold)).into_try()
2658     }
2659
2660     #[inline]
2661     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2662     where
2663         Self: Sized,
2664         Fold: FnMut(Acc, Self::Item) -> Acc,
2665     {
2666         #[inline]
2667         fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2668             move |acc, x| Ok(f(acc, x))
2669         }
2670
2671         self.try_fold(init, ok(fold)).unwrap()
2672     }
2673 }
2674
2675 #[unstable(issue = "0", feature = "inplace_iteration")]
2676 unsafe impl<St, F, B, S: Iterator, I: Iterator> SourceIter for Scan<I, St, F>
2677     where I: SourceIter<Source = S>,
2678           F: FnMut(&mut St, I::Item) -> Option<B>,
2679 {
2680     type Source = S;
2681
2682     #[inline]
2683     unsafe fn as_inner(&mut self) -> &mut S {
2684         // Safety: unsafe function forwarding to unsafe function with the same requirements
2685         unsafe { SourceIter::as_inner(&mut self.iter) }
2686     }
2687 }
2688
2689 #[unstable(issue = "0", feature = "inplace_iteration")]
2690 unsafe impl<St, F, B, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F>
2691     where F: FnMut(&mut St, I::Item) -> Option<B>,
2692 {}
2693
2694 /// An iterator that calls a function with a reference to each element before
2695 /// yielding it.
2696 ///
2697 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2698 /// documentation for more.
2699 ///
2700 /// [`inspect`]: trait.Iterator.html#method.inspect
2701 /// [`Iterator`]: trait.Iterator.html
2702 #[must_use = "iterators are lazy and do nothing unless consumed"]
2703 #[stable(feature = "rust1", since = "1.0.0")]
2704 #[derive(Clone)]
2705 pub struct Inspect<I, F> {
2706     iter: I,
2707     f: F,
2708 }
2709 impl<I, F> Inspect<I, F> {
2710     pub(super) fn new(iter: I, f: F) -> Inspect<I, F> {
2711         Inspect { iter, f }
2712     }
2713 }
2714
2715 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2716 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2717     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2718         f.debug_struct("Inspect").field("iter", &self.iter).finish()
2719     }
2720 }
2721
2722 impl<I: Iterator, F> Inspect<I, F>
2723 where
2724     F: FnMut(&I::Item),
2725 {
2726     #[inline]
2727     fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2728         if let Some(ref a) = elt {
2729             (self.f)(a);
2730         }
2731
2732         elt
2733     }
2734 }
2735
2736 fn inspect_fold<T, Acc>(
2737     mut f: impl FnMut(&T),
2738     mut fold: impl FnMut(Acc, T) -> Acc,
2739 ) -> impl FnMut(Acc, T) -> Acc {
2740     move |acc, item| {
2741         f(&item);
2742         fold(acc, item)
2743     }
2744 }
2745
2746 fn inspect_try_fold<'a, T, Acc, R>(
2747     f: &'a mut impl FnMut(&T),
2748     mut fold: impl FnMut(Acc, T) -> R + 'a,
2749 ) -> impl FnMut(Acc, T) -> R + 'a {
2750     move |acc, item| {
2751         f(&item);
2752         fold(acc, item)
2753     }
2754 }
2755
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 impl<I: Iterator, F> Iterator for Inspect<I, F>
2758 where
2759     F: FnMut(&I::Item),
2760 {
2761     type Item = I::Item;
2762
2763     #[inline]
2764     fn next(&mut self) -> Option<I::Item> {
2765         let next = self.iter.next();
2766         self.do_inspect(next)
2767     }
2768
2769     #[inline]
2770     fn size_hint(&self) -> (usize, Option<usize>) {
2771         self.iter.size_hint()
2772     }
2773
2774     #[inline]
2775     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2776     where
2777         Self: Sized,
2778         Fold: FnMut(Acc, Self::Item) -> R,
2779         R: Try<Ok = Acc>,
2780     {
2781         self.iter.try_fold(init, inspect_try_fold(&mut self.f, fold))
2782     }
2783
2784     #[inline]
2785     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2786     where
2787         Fold: FnMut(Acc, Self::Item) -> Acc,
2788     {
2789         self.iter.fold(init, inspect_fold(self.f, fold))
2790     }
2791 }
2792
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2795 where
2796     F: FnMut(&I::Item),
2797 {
2798     #[inline]
2799     fn next_back(&mut self) -> Option<I::Item> {
2800         let next = self.iter.next_back();
2801         self.do_inspect(next)
2802     }
2803
2804     #[inline]
2805     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
2806     where
2807         Self: Sized,
2808         Fold: FnMut(Acc, Self::Item) -> R,
2809         R: Try<Ok = Acc>,
2810     {
2811         self.iter.try_rfold(init, inspect_try_fold(&mut self.f, fold))
2812     }
2813
2814     #[inline]
2815     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2816     where
2817         Fold: FnMut(Acc, Self::Item) -> Acc,
2818     {
2819         self.iter.rfold(init, inspect_fold(self.f, fold))
2820     }
2821 }
2822
2823 #[stable(feature = "rust1", since = "1.0.0")]
2824 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2825 where
2826     F: FnMut(&I::Item),
2827 {
2828     fn len(&self) -> usize {
2829         self.iter.len()
2830     }
2831
2832     fn is_empty(&self) -> bool {
2833         self.iter.is_empty()
2834     }
2835 }
2836
2837 #[stable(feature = "fused", since = "1.26.0")]
2838 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F> where F: FnMut(&I::Item) {}
2839
2840 #[unstable(issue = "0", feature = "inplace_iteration")]
2841 unsafe impl<S: Iterator, I: Iterator, F> SourceIter for Inspect<I, F> where
2842     F: FnMut(&I::Item),
2843     I: SourceIter<Source = S>
2844 {
2845     type Source = S;
2846
2847     #[inline]
2848     unsafe fn as_inner(&mut self) -> &mut S {
2849         // Safety: unsafe function forwarding to unsafe function with the same requirements
2850         unsafe { SourceIter::as_inner(&mut self.iter) }
2851     }
2852 }
2853
2854 #[unstable(issue = "0", feature = "inplace_iteration")]
2855 unsafe impl<I: InPlaceIterable, F> InPlaceIterable for Inspect<I, F> where F: FnMut(&I::Item)  {}
2856
2857 /// An iterator adapter that produces output as long as the underlying
2858 /// iterator produces `Result::Ok` values.
2859 ///
2860 /// If an error is encountered, the iterator stops and the error is
2861 /// stored.
2862 pub(crate) struct ResultShunt<'a, I, E> {
2863     iter: I,
2864     error: &'a mut Result<(), E>,
2865 }
2866
2867 /// Process the given iterator as if it yielded a `T` instead of a
2868 /// `Result<T, _>`. Any errors will stop the inner iterator and
2869 /// the overall result will be an error.
2870 pub(crate) fn process_results<I, T, E, F, U>(iter: I, mut f: F) -> Result<U, E>
2871 where
2872     I: Iterator<Item = Result<T, E>>,
2873     for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U,
2874 {
2875     let mut error = Ok(());
2876     let shunt = ResultShunt { iter, error: &mut error };
2877     let value = f(shunt);
2878     error.map(|()| value)
2879 }
2880
2881 impl<I, T, E> Iterator for ResultShunt<'_, I, E>
2882 where
2883     I: Iterator<Item = Result<T, E>>,
2884 {
2885     type Item = T;
2886
2887     fn next(&mut self) -> Option<Self::Item> {
2888         self.find(|_| true)
2889     }
2890
2891     fn size_hint(&self) -> (usize, Option<usize>) {
2892         if self.error.is_err() {
2893             (0, Some(0))
2894         } else {
2895             let (_, upper) = self.iter.size_hint();
2896             (0, upper)
2897         }
2898     }
2899
2900     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2901     where
2902         F: FnMut(B, Self::Item) -> R,
2903         R: Try<Ok = B>,
2904     {
2905         let error = &mut *self.error;
2906         self.iter
2907             .try_fold(init, |acc, x| match x {
2908                 Ok(x) => ControlFlow::from_try(f(acc, x)),
2909                 Err(e) => {
2910                     *error = Err(e);
2911                     ControlFlow::Break(Try::from_ok(acc))
2912                 }
2913             })
2914             .into_try()
2915     }
2916
2917     fn fold<B, F>(mut self, init: B, fold: F) -> B
2918     where
2919         Self: Sized,
2920         F: FnMut(B, Self::Item) -> B,
2921     {
2922         #[inline]
2923         fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> {
2924             move |acc, x| Ok(f(acc, x))
2925         }
2926
2927         self.try_fold(init, ok(fold)).unwrap()
2928     }
2929 }