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