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