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