]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/mod.rs
86b297557dddb3961e98fbe33d4549485b59b513
[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.start <= self.iter.end) {
791             return None;
792         }
793         // add 1 to self.step to get original step size back
794         // it was decremented for the general case on construction
795         if let Some(n) = self.iter.start.add_usize(self.step+1) {
796             let next = mem::replace(&mut self.iter.start, n);
797             Some(next)
798         } else {
799             let last = self.iter.start.replace_one();
800             self.iter.end.replace_zero();
801             Some(last)
802         }
803     }
804 }
805
806 // StepBy can only make the iterator shorter, so the len will still fit.
807 #[stable(feature = "iterator_step_by", since = "1.28.0")]
808 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
809
810 /// An iterator that strings two iterators together.
811 ///
812 /// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
813 /// documentation for more.
814 ///
815 /// [`chain`]: trait.Iterator.html#method.chain
816 /// [`Iterator`]: trait.Iterator.html
817 #[derive(Clone, Debug)]
818 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub struct Chain<A, B> {
821     a: A,
822     b: B,
823     state: ChainState,
824 }
825
826 // The iterator protocol specifies that iteration ends with the return value
827 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
828 // further calls return. The chain adaptor must account for this since it uses
829 // two subiterators.
830 //
831 //  It uses three states:
832 //
833 //  - Both: `a` and `b` are remaining
834 //  - Front: `a` remaining
835 //  - Back: `b` remaining
836 //
837 //  The fourth state (neither iterator is remaining) only occurs after Chain has
838 //  returned None once, so we don't need to store this state.
839 #[derive(Clone, Debug)]
840 enum ChainState {
841     // both front and back iterator are remaining
842     Both,
843     // only front is remaining
844     Front,
845     // only back is remaining
846     Back,
847 }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<A, B> Iterator for Chain<A, B> where
851     A: Iterator,
852     B: Iterator<Item = A::Item>
853 {
854     type Item = A::Item;
855
856     #[inline]
857     fn next(&mut self) -> Option<A::Item> {
858         match self.state {
859             ChainState::Both => match self.a.next() {
860                 elt @ Some(..) => elt,
861                 None => {
862                     self.state = ChainState::Back;
863                     self.b.next()
864                 }
865             },
866             ChainState::Front => self.a.next(),
867             ChainState::Back => self.b.next(),
868         }
869     }
870
871     #[inline]
872     #[rustc_inherit_overflow_checks]
873     fn count(self) -> usize {
874         match self.state {
875             ChainState::Both => self.a.count() + self.b.count(),
876             ChainState::Front => self.a.count(),
877             ChainState::Back => self.b.count(),
878         }
879     }
880
881     fn try_fold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
882         Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
883     {
884         let mut accum = init;
885         match self.state {
886             ChainState::Both | ChainState::Front => {
887                 accum = self.a.try_fold(accum, &mut f)?;
888                 if let ChainState::Both = self.state {
889                     self.state = ChainState::Back;
890                 }
891             }
892             _ => { }
893         }
894         if let ChainState::Back = self.state {
895             accum = self.b.try_fold(accum, &mut f)?;
896         }
897         Try::from_ok(accum)
898     }
899
900     fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
901         where F: FnMut(Acc, Self::Item) -> Acc,
902     {
903         let mut accum = init;
904         match self.state {
905             ChainState::Both | ChainState::Front => {
906                 accum = self.a.fold(accum, &mut f);
907             }
908             _ => { }
909         }
910         match self.state {
911             ChainState::Both | ChainState::Back => {
912                 accum = self.b.fold(accum, &mut f);
913             }
914             _ => { }
915         }
916         accum
917     }
918
919     #[inline]
920     fn nth(&mut self, mut n: usize) -> Option<A::Item> {
921         match self.state {
922             ChainState::Both | ChainState::Front => {
923                 for x in self.a.by_ref() {
924                     if n == 0 {
925                         return Some(x)
926                     }
927                     n -= 1;
928                 }
929                 if let ChainState::Both = self.state {
930                     self.state = ChainState::Back;
931                 }
932             }
933             ChainState::Back => {}
934         }
935         if let ChainState::Back = self.state {
936             self.b.nth(n)
937         } else {
938             None
939         }
940     }
941
942     #[inline]
943     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
944         P: FnMut(&Self::Item) -> bool,
945     {
946         match self.state {
947             ChainState::Both => match self.a.find(&mut predicate) {
948                 None => {
949                     self.state = ChainState::Back;
950                     self.b.find(predicate)
951                 }
952                 v => v
953             },
954             ChainState::Front => self.a.find(predicate),
955             ChainState::Back => self.b.find(predicate),
956         }
957     }
958
959     #[inline]
960     fn last(self) -> Option<A::Item> {
961         match self.state {
962             ChainState::Both => {
963                 // Must exhaust a before b.
964                 let a_last = self.a.last();
965                 let b_last = self.b.last();
966                 b_last.or(a_last)
967             },
968             ChainState::Front => self.a.last(),
969             ChainState::Back => self.b.last()
970         }
971     }
972
973     #[inline]
974     fn size_hint(&self) -> (usize, Option<usize>) {
975         let (a_lower, a_upper) = self.a.size_hint();
976         let (b_lower, b_upper) = self.b.size_hint();
977
978         let lower = a_lower.saturating_add(b_lower);
979
980         let upper = match (a_upper, b_upper) {
981             (Some(x), Some(y)) => x.checked_add(y),
982             _ => None
983         };
984
985         (lower, upper)
986     }
987 }
988
989 #[stable(feature = "rust1", since = "1.0.0")]
990 impl<A, B> DoubleEndedIterator for Chain<A, B> where
991     A: DoubleEndedIterator,
992     B: DoubleEndedIterator<Item=A::Item>,
993 {
994     #[inline]
995     fn next_back(&mut self) -> Option<A::Item> {
996         match self.state {
997             ChainState::Both => match self.b.next_back() {
998                 elt @ Some(..) => elt,
999                 None => {
1000                     self.state = ChainState::Front;
1001                     self.a.next_back()
1002                 }
1003             },
1004             ChainState::Front => self.a.next_back(),
1005             ChainState::Back => self.b.next_back(),
1006         }
1007     }
1008
1009     fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
1010         Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1011     {
1012         let mut accum = init;
1013         match self.state {
1014             ChainState::Both | ChainState::Back => {
1015                 accum = self.b.try_rfold(accum, &mut f)?;
1016                 if let ChainState::Both = self.state {
1017                     self.state = ChainState::Front;
1018                 }
1019             }
1020             _ => { }
1021         }
1022         if let ChainState::Front = self.state {
1023             accum = self.a.try_rfold(accum, &mut f)?;
1024         }
1025         Try::from_ok(accum)
1026     }
1027
1028     fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc
1029         where F: FnMut(Acc, Self::Item) -> Acc,
1030     {
1031         let mut accum = init;
1032         match self.state {
1033             ChainState::Both | ChainState::Back => {
1034                 accum = self.b.rfold(accum, &mut f);
1035             }
1036             _ => { }
1037         }
1038         match self.state {
1039             ChainState::Both | ChainState::Front => {
1040                 accum = self.a.rfold(accum, &mut f);
1041             }
1042             _ => { }
1043         }
1044         accum
1045     }
1046
1047 }
1048
1049 // Note: *both* must be fused to handle double-ended iterators.
1050 #[stable(feature = "fused", since = "1.26.0")]
1051 impl<A, B> FusedIterator for Chain<A, B>
1052     where A: FusedIterator,
1053           B: FusedIterator<Item=A::Item>,
1054 {}
1055
1056 #[unstable(feature = "trusted_len", issue = "37572")]
1057 unsafe impl<A, B> TrustedLen for Chain<A, B>
1058     where A: TrustedLen, B: TrustedLen<Item=A::Item>,
1059 {}
1060
1061 /// An iterator that iterates two other iterators simultaneously.
1062 ///
1063 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
1064 /// documentation for more.
1065 ///
1066 /// [`zip`]: trait.Iterator.html#method.zip
1067 /// [`Iterator`]: trait.Iterator.html
1068 #[derive(Clone, Debug)]
1069 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub struct Zip<A, B> {
1072     a: A,
1073     b: B,
1074     // index and len are only used by the specialized version of zip
1075     index: usize,
1076     len: usize,
1077 }
1078
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
1081 {
1082     type Item = (A::Item, B::Item);
1083
1084     #[inline]
1085     fn next(&mut self) -> Option<Self::Item> {
1086         ZipImpl::next(self)
1087     }
1088
1089     #[inline]
1090     fn size_hint(&self) -> (usize, Option<usize>) {
1091         ZipImpl::size_hint(self)
1092     }
1093
1094     #[inline]
1095     fn nth(&mut self, n: usize) -> Option<Self::Item> {
1096         ZipImpl::nth(self, n)
1097     }
1098 }
1099
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<A, B> DoubleEndedIterator for Zip<A, B> where
1102     A: DoubleEndedIterator + ExactSizeIterator,
1103     B: DoubleEndedIterator + ExactSizeIterator,
1104 {
1105     #[inline]
1106     fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
1107         ZipImpl::next_back(self)
1108     }
1109 }
1110
1111 // Zip specialization trait
1112 #[doc(hidden)]
1113 trait ZipImpl<A, B> {
1114     type Item;
1115     fn new(a: A, b: B) -> Self;
1116     fn next(&mut self) -> Option<Self::Item>;
1117     fn size_hint(&self) -> (usize, Option<usize>);
1118     fn nth(&mut self, n: usize) -> Option<Self::Item>;
1119     fn super_nth(&mut self, mut n: usize) -> Option<Self::Item> {
1120         while let Some(x) = self.next() {
1121             if n == 0 { return Some(x) }
1122             n -= 1;
1123         }
1124         None
1125     }
1126     fn next_back(&mut self) -> Option<Self::Item>
1127         where A: DoubleEndedIterator + ExactSizeIterator,
1128               B: DoubleEndedIterator + ExactSizeIterator;
1129 }
1130
1131 // General Zip impl
1132 #[doc(hidden)]
1133 impl<A, B> ZipImpl<A, B> for Zip<A, B>
1134     where A: Iterator, B: Iterator
1135 {
1136     type Item = (A::Item, B::Item);
1137     default fn new(a: A, b: B) -> Self {
1138         Zip {
1139             a,
1140             b,
1141             index: 0, // unused
1142             len: 0, // unused
1143         }
1144     }
1145
1146     #[inline]
1147     default fn next(&mut self) -> Option<(A::Item, B::Item)> {
1148         self.a.next().and_then(|x| {
1149             self.b.next().and_then(|y| {
1150                 Some((x, y))
1151             })
1152         })
1153     }
1154
1155     #[inline]
1156     default fn nth(&mut self, n: usize) -> Option<Self::Item> {
1157         self.super_nth(n)
1158     }
1159
1160     #[inline]
1161     default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
1162         where A: DoubleEndedIterator + ExactSizeIterator,
1163               B: DoubleEndedIterator + ExactSizeIterator
1164     {
1165         let a_sz = self.a.len();
1166         let b_sz = self.b.len();
1167         if a_sz != b_sz {
1168             // Adjust a, b to equal length
1169             if a_sz > b_sz {
1170                 for _ in 0..a_sz - b_sz { self.a.next_back(); }
1171             } else {
1172                 for _ in 0..b_sz - a_sz { self.b.next_back(); }
1173             }
1174         }
1175         match (self.a.next_back(), self.b.next_back()) {
1176             (Some(x), Some(y)) => Some((x, y)),
1177             (None, None) => None,
1178             _ => unreachable!(),
1179         }
1180     }
1181
1182     #[inline]
1183     default fn size_hint(&self) -> (usize, Option<usize>) {
1184         let (a_lower, a_upper) = self.a.size_hint();
1185         let (b_lower, b_upper) = self.b.size_hint();
1186
1187         let lower = cmp::min(a_lower, b_lower);
1188
1189         let upper = match (a_upper, b_upper) {
1190             (Some(x), Some(y)) => Some(cmp::min(x,y)),
1191             (Some(x), None) => Some(x),
1192             (None, Some(y)) => Some(y),
1193             (None, None) => None
1194         };
1195
1196         (lower, upper)
1197     }
1198 }
1199
1200 #[doc(hidden)]
1201 impl<A, B> ZipImpl<A, B> for Zip<A, B>
1202     where A: TrustedRandomAccess, B: TrustedRandomAccess
1203 {
1204     fn new(a: A, b: B) -> Self {
1205         let len = cmp::min(a.len(), b.len());
1206         Zip {
1207             a,
1208             b,
1209             index: 0,
1210             len,
1211         }
1212     }
1213
1214     #[inline]
1215     fn next(&mut self) -> Option<(A::Item, B::Item)> {
1216         if self.index < self.len {
1217             let i = self.index;
1218             self.index += 1;
1219             unsafe {
1220                 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
1221             }
1222         } else if A::may_have_side_effect() && self.index < self.a.len() {
1223             // match the base implementation's potential side effects
1224             unsafe {
1225                 self.a.get_unchecked(self.index);
1226             }
1227             self.index += 1;
1228             None
1229         } else {
1230             None
1231         }
1232     }
1233
1234     #[inline]
1235     fn size_hint(&self) -> (usize, Option<usize>) {
1236         let len = self.len - self.index;
1237         (len, Some(len))
1238     }
1239
1240     #[inline]
1241     fn nth(&mut self, n: usize) -> Option<Self::Item> {
1242         let delta = cmp::min(n, self.len - self.index);
1243         let end = self.index + delta;
1244         while self.index < end {
1245             let i = self.index;
1246             self.index += 1;
1247             if A::may_have_side_effect() {
1248                 unsafe { self.a.get_unchecked(i); }
1249             }
1250             if B::may_have_side_effect() {
1251                 unsafe { self.b.get_unchecked(i); }
1252             }
1253         }
1254
1255         self.super_nth(n - delta)
1256     }
1257
1258     #[inline]
1259     fn next_back(&mut self) -> Option<(A::Item, B::Item)>
1260         where A: DoubleEndedIterator + ExactSizeIterator,
1261               B: DoubleEndedIterator + ExactSizeIterator
1262     {
1263         // Adjust a, b to equal length
1264         if A::may_have_side_effect() {
1265             let sz = self.a.len();
1266             if sz > self.len {
1267                 for _ in 0..sz - cmp::max(self.len, self.index) {
1268                     self.a.next_back();
1269                 }
1270             }
1271         }
1272         if B::may_have_side_effect() {
1273             let sz = self.b.len();
1274             if sz > self.len {
1275                 for _ in 0..sz - self.len {
1276                     self.b.next_back();
1277                 }
1278             }
1279         }
1280         if self.index < self.len {
1281             self.len -= 1;
1282             let i = self.len;
1283             unsafe {
1284                 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
1285             }
1286         } else {
1287             None
1288         }
1289     }
1290 }
1291
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<A, B> ExactSizeIterator for Zip<A, B>
1294     where A: ExactSizeIterator, B: ExactSizeIterator {}
1295
1296 #[doc(hidden)]
1297 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
1298     where A: TrustedRandomAccess,
1299           B: TrustedRandomAccess,
1300 {
1301     unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
1302         (self.a.get_unchecked(i), self.b.get_unchecked(i))
1303     }
1304
1305     fn may_have_side_effect() -> bool {
1306         A::may_have_side_effect() || B::may_have_side_effect()
1307     }
1308 }
1309
1310 #[stable(feature = "fused", since = "1.26.0")]
1311 impl<A, B> FusedIterator for Zip<A, B>
1312     where A: FusedIterator, B: FusedIterator, {}
1313
1314 #[unstable(feature = "trusted_len", issue = "37572")]
1315 unsafe impl<A, B> TrustedLen for Zip<A, B>
1316     where A: TrustedLen, B: TrustedLen,
1317 {}
1318
1319 /// An iterator that maps the values of `iter` with `f`.
1320 ///
1321 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
1322 /// documentation for more.
1323 ///
1324 /// [`map`]: trait.Iterator.html#method.map
1325 /// [`Iterator`]: trait.Iterator.html
1326 ///
1327 /// # Notes about side effects
1328 ///
1329 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
1330 /// you can also [`map`] backwards:
1331 ///
1332 /// ```rust
1333 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
1334 ///
1335 /// assert_eq!(v, [4, 3, 2]);
1336 /// ```
1337 ///
1338 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1339 ///
1340 /// But if your closure has state, iterating backwards may act in a way you do
1341 /// not expect. Let's go through an example. First, in the forward direction:
1342 ///
1343 /// ```rust
1344 /// let mut c = 0;
1345 ///
1346 /// for pair in vec!['a', 'b', 'c'].into_iter()
1347 ///                                .map(|letter| { c += 1; (letter, c) }) {
1348 ///     println!("{:?}", pair);
1349 /// }
1350 /// ```
1351 ///
1352 /// This will print "('a', 1), ('b', 2), ('c', 3)".
1353 ///
1354 /// Now consider this twist where we add a call to `rev`. This version will
1355 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
1356 /// but the values of the counter still go in order. This is because `map()` is
1357 /// still being called lazily on each item, but we are popping items off the
1358 /// back of the vector now, instead of shifting them from the front.
1359 ///
1360 /// ```rust
1361 /// let mut c = 0;
1362 ///
1363 /// for pair in vec!['a', 'b', 'c'].into_iter()
1364 ///                                .map(|letter| { c += 1; (letter, c) })
1365 ///                                .rev() {
1366 ///     println!("{:?}", pair);
1367 /// }
1368 /// ```
1369 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 #[derive(Clone)]
1372 pub struct Map<I, F> {
1373     iter: I,
1374     f: F,
1375 }
1376
1377 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1378 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
1379     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380         f.debug_struct("Map")
1381             .field("iter", &self.iter)
1382             .finish()
1383     }
1384 }
1385
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
1388     type Item = B;
1389
1390     #[inline]
1391     fn next(&mut self) -> Option<B> {
1392         self.iter.next().map(&mut self.f)
1393     }
1394
1395     #[inline]
1396     fn size_hint(&self) -> (usize, Option<usize>) {
1397         self.iter.size_hint()
1398     }
1399
1400     fn try_fold<Acc, G, R>(&mut self, init: Acc, mut g: G) -> R where
1401         Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1402     {
1403         let f = &mut self.f;
1404         self.iter.try_fold(init, move |acc, elt| g(acc, f(elt)))
1405     }
1406
1407     fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1408         where G: FnMut(Acc, Self::Item) -> Acc,
1409     {
1410         let mut f = self.f;
1411         self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1412     }
1413 }
1414
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1417     F: FnMut(I::Item) -> B,
1418 {
1419     #[inline]
1420     fn next_back(&mut self) -> Option<B> {
1421         self.iter.next_back().map(&mut self.f)
1422     }
1423
1424     fn try_rfold<Acc, G, R>(&mut self, init: Acc, mut g: G) -> R where
1425         Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1426     {
1427         let f = &mut self.f;
1428         self.iter.try_rfold(init, move |acc, elt| g(acc, f(elt)))
1429     }
1430
1431     fn rfold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1432         where G: FnMut(Acc, Self::Item) -> Acc,
1433     {
1434         let mut f = self.f;
1435         self.iter.rfold(init, move |acc, elt| g(acc, f(elt)))
1436     }
1437 }
1438
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1441     where F: FnMut(I::Item) -> B
1442 {
1443     fn len(&self) -> usize {
1444         self.iter.len()
1445     }
1446
1447     fn is_empty(&self) -> bool {
1448         self.iter.is_empty()
1449     }
1450 }
1451
1452 #[stable(feature = "fused", since = "1.26.0")]
1453 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1454     where F: FnMut(I::Item) -> B {}
1455
1456 #[unstable(feature = "trusted_len", issue = "37572")]
1457 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1458     where I: TrustedLen,
1459           F: FnMut(I::Item) -> B {}
1460
1461 #[doc(hidden)]
1462 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1463     where I: TrustedRandomAccess,
1464           F: FnMut(I::Item) -> B,
1465 {
1466     unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1467         (self.f)(self.iter.get_unchecked(i))
1468     }
1469     #[inline]
1470     fn may_have_side_effect() -> bool { true }
1471 }
1472
1473 /// An iterator that filters the elements of `iter` with `predicate`.
1474 ///
1475 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1476 /// documentation for more.
1477 ///
1478 /// [`filter`]: trait.Iterator.html#method.filter
1479 /// [`Iterator`]: trait.Iterator.html
1480 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 #[derive(Clone)]
1483 pub struct Filter<I, P> {
1484     iter: I,
1485     predicate: P,
1486 }
1487
1488 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1489 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1490     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491         f.debug_struct("Filter")
1492             .field("iter", &self.iter)
1493             .finish()
1494     }
1495 }
1496
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1499     type Item = I::Item;
1500
1501     #[inline]
1502     fn next(&mut self) -> Option<I::Item> {
1503         for x in &mut self.iter {
1504             if (self.predicate)(&x) {
1505                 return Some(x);
1506             }
1507         }
1508         None
1509     }
1510
1511     #[inline]
1512     fn size_hint(&self) -> (usize, Option<usize>) {
1513         let (_, upper) = self.iter.size_hint();
1514         (0, upper) // can't know a lower bound, due to the predicate
1515     }
1516
1517     // this special case allows the compiler to make `.filter(_).count()`
1518     // branchless. Barring perfect branch prediction (which is unattainable in
1519     // the general case), this will be much faster in >90% of cases (containing
1520     // virtually all real workloads) and only a tiny bit slower in the rest.
1521     //
1522     // Having this specialization thus allows us to write `.filter(p).count()`
1523     // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1524     // less readable and also less backwards-compatible to Rust before 1.10.
1525     //
1526     // Using the branchless version will also simplify the LLVM byte code, thus
1527     // leaving more budget for LLVM optimizations.
1528     #[inline]
1529     fn count(mut self) -> usize {
1530         let mut count = 0;
1531         for x in &mut self.iter {
1532             count += (self.predicate)(&x) as usize;
1533         }
1534         count
1535     }
1536
1537     #[inline]
1538     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1539         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1540     {
1541         let predicate = &mut self.predicate;
1542         self.iter.try_fold(init, move |acc, item| if predicate(&item) {
1543             fold(acc, item)
1544         } else {
1545             Try::from_ok(acc)
1546         })
1547     }
1548
1549     #[inline]
1550     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1551         where Fold: FnMut(Acc, Self::Item) -> Acc,
1552     {
1553         let mut predicate = self.predicate;
1554         self.iter.fold(init, move |acc, item| if predicate(&item) {
1555             fold(acc, item)
1556         } else {
1557             acc
1558         })
1559     }
1560 }
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1564     where P: FnMut(&I::Item) -> bool,
1565 {
1566     #[inline]
1567     fn next_back(&mut self) -> Option<I::Item> {
1568         for x in self.iter.by_ref().rev() {
1569             if (self.predicate)(&x) {
1570                 return Some(x);
1571             }
1572         }
1573         None
1574     }
1575
1576     #[inline]
1577     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1578         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1579     {
1580         let predicate = &mut self.predicate;
1581         self.iter.try_rfold(init, move |acc, item| if predicate(&item) {
1582             fold(acc, item)
1583         } else {
1584             Try::from_ok(acc)
1585         })
1586     }
1587
1588     #[inline]
1589     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1590         where Fold: FnMut(Acc, Self::Item) -> Acc,
1591     {
1592         let mut predicate = self.predicate;
1593         self.iter.rfold(init, move |acc, item| if predicate(&item) {
1594             fold(acc, item)
1595         } else {
1596             acc
1597         })
1598     }
1599 }
1600
1601 #[stable(feature = "fused", since = "1.26.0")]
1602 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1603     where P: FnMut(&I::Item) -> bool {}
1604
1605 /// An iterator that uses `f` to both filter and map elements from `iter`.
1606 ///
1607 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1608 /// documentation for more.
1609 ///
1610 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1611 /// [`Iterator`]: trait.Iterator.html
1612 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 #[derive(Clone)]
1615 pub struct FilterMap<I, F> {
1616     iter: I,
1617     f: F,
1618 }
1619
1620 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1621 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1622     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1623         f.debug_struct("FilterMap")
1624             .field("iter", &self.iter)
1625             .finish()
1626     }
1627 }
1628
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1631     where F: FnMut(I::Item) -> Option<B>,
1632 {
1633     type Item = B;
1634
1635     #[inline]
1636     fn next(&mut self) -> Option<B> {
1637         for x in self.iter.by_ref() {
1638             if let Some(y) = (self.f)(x) {
1639                 return Some(y);
1640             }
1641         }
1642         None
1643     }
1644
1645     #[inline]
1646     fn size_hint(&self) -> (usize, Option<usize>) {
1647         let (_, upper) = self.iter.size_hint();
1648         (0, upper) // can't know a lower bound, due to the predicate
1649     }
1650
1651     #[inline]
1652     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1653         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1654     {
1655         let f = &mut self.f;
1656         self.iter.try_fold(init, move |acc, item| match f(item) {
1657             Some(x) => fold(acc, x),
1658             None => Try::from_ok(acc),
1659         })
1660     }
1661
1662     #[inline]
1663     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1664         where Fold: FnMut(Acc, Self::Item) -> Acc,
1665     {
1666         let mut f = self.f;
1667         self.iter.fold(init, move |acc, item| match f(item) {
1668             Some(x) => fold(acc, x),
1669             None => acc,
1670         })
1671     }
1672 }
1673
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1676     where F: FnMut(I::Item) -> Option<B>,
1677 {
1678     #[inline]
1679     fn next_back(&mut self) -> Option<B> {
1680         for x in self.iter.by_ref().rev() {
1681             if let Some(y) = (self.f)(x) {
1682                 return Some(y);
1683             }
1684         }
1685         None
1686     }
1687
1688     #[inline]
1689     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1690         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1691     {
1692         let f = &mut self.f;
1693         self.iter.try_rfold(init, move |acc, item| match f(item) {
1694             Some(x) => fold(acc, x),
1695             None => Try::from_ok(acc),
1696         })
1697     }
1698
1699     #[inline]
1700     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1701         where Fold: FnMut(Acc, Self::Item) -> Acc,
1702     {
1703         let mut f = self.f;
1704         self.iter.rfold(init, move |acc, item| match f(item) {
1705             Some(x) => fold(acc, x),
1706             None => acc,
1707         })
1708     }
1709 }
1710
1711 #[stable(feature = "fused", since = "1.26.0")]
1712 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1713     where F: FnMut(I::Item) -> Option<B> {}
1714
1715 /// An iterator that yields the current count and the element during iteration.
1716 ///
1717 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1718 /// documentation for more.
1719 ///
1720 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1721 /// [`Iterator`]: trait.Iterator.html
1722 #[derive(Clone, Debug)]
1723 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 pub struct Enumerate<I> {
1726     iter: I,
1727     count: usize,
1728 }
1729
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<I> Iterator for Enumerate<I> where I: Iterator {
1732     type Item = (usize, <I as Iterator>::Item);
1733
1734     /// # Overflow Behavior
1735     ///
1736     /// The method does no guarding against overflows, so enumerating more than
1737     /// `usize::MAX` elements either produces the wrong result or panics. If
1738     /// debug assertions are enabled, a panic is guaranteed.
1739     ///
1740     /// # Panics
1741     ///
1742     /// Might panic if the index of the element overflows a `usize`.
1743     #[inline]
1744     #[rustc_inherit_overflow_checks]
1745     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1746         self.iter.next().map(|a| {
1747             let ret = (self.count, a);
1748             // Possible undefined overflow.
1749             self.count += 1;
1750             ret
1751         })
1752     }
1753
1754     #[inline]
1755     fn size_hint(&self) -> (usize, Option<usize>) {
1756         self.iter.size_hint()
1757     }
1758
1759     #[inline]
1760     #[rustc_inherit_overflow_checks]
1761     fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1762         self.iter.nth(n).map(|a| {
1763             let i = self.count + n;
1764             self.count = i + 1;
1765             (i, a)
1766         })
1767     }
1768
1769     #[inline]
1770     fn count(self) -> usize {
1771         self.iter.count()
1772     }
1773
1774     #[inline]
1775     #[rustc_inherit_overflow_checks]
1776     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1777         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1778     {
1779         let count = &mut self.count;
1780         self.iter.try_fold(init, move |acc, item| {
1781             let acc = fold(acc, (*count, item));
1782             *count += 1;
1783             acc
1784         })
1785     }
1786
1787     #[inline]
1788     #[rustc_inherit_overflow_checks]
1789     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1790         where Fold: FnMut(Acc, Self::Item) -> Acc,
1791     {
1792         let mut count = self.count;
1793         self.iter.fold(init, move |acc, item| {
1794             let acc = fold(acc, (count, item));
1795             count += 1;
1796             acc
1797         })
1798     }
1799 }
1800
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<I> DoubleEndedIterator for Enumerate<I> where
1803     I: ExactSizeIterator + DoubleEndedIterator
1804 {
1805     #[inline]
1806     fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1807         self.iter.next_back().map(|a| {
1808             let len = self.iter.len();
1809             // Can safely add, `ExactSizeIterator` promises that the number of
1810             // elements fits into a `usize`.
1811             (self.count + len, a)
1812         })
1813     }
1814
1815     #[inline]
1816     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1817         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1818     {
1819         // Can safely add and subtract the count, as `ExactSizeIterator` promises
1820         // that the number of elements fits into a `usize`.
1821         let mut count = self.count + self.iter.len();
1822         self.iter.try_rfold(init, move |acc, item| {
1823             count -= 1;
1824             fold(acc, (count, item))
1825         })
1826     }
1827
1828     #[inline]
1829     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1830         where Fold: FnMut(Acc, Self::Item) -> Acc,
1831     {
1832         // Can safely add and subtract the count, as `ExactSizeIterator` promises
1833         // that the number of elements fits into a `usize`.
1834         let mut count = self.count + self.iter.len();
1835         self.iter.rfold(init, move |acc, item| {
1836             count -= 1;
1837             fold(acc, (count, item))
1838         })
1839     }
1840 }
1841
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1844     fn len(&self) -> usize {
1845         self.iter.len()
1846     }
1847
1848     fn is_empty(&self) -> bool {
1849         self.iter.is_empty()
1850     }
1851 }
1852
1853 #[doc(hidden)]
1854 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1855     where I: TrustedRandomAccess
1856 {
1857     unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1858         (self.count + i, self.iter.get_unchecked(i))
1859     }
1860
1861     fn may_have_side_effect() -> bool {
1862         I::may_have_side_effect()
1863     }
1864 }
1865
1866 #[stable(feature = "fused", since = "1.26.0")]
1867 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1868
1869 #[unstable(feature = "trusted_len", issue = "37572")]
1870 unsafe impl<I> TrustedLen for Enumerate<I>
1871     where I: TrustedLen,
1872 {}
1873
1874
1875 /// An iterator with a `peek()` that returns an optional reference to the next
1876 /// element.
1877 ///
1878 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1879 /// documentation for more.
1880 ///
1881 /// [`peekable`]: trait.Iterator.html#method.peekable
1882 /// [`Iterator`]: trait.Iterator.html
1883 #[derive(Clone, Debug)]
1884 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub struct Peekable<I: Iterator> {
1887     iter: I,
1888     /// Remember a peeked value, even if it was None.
1889     peeked: Option<Option<I::Item>>,
1890 }
1891
1892 // Peekable must remember if a None has been seen in the `.peek()` method.
1893 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1894 // underlying iterator at most once. This does not by itself make the iterator
1895 // fused.
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 impl<I: Iterator> Iterator for Peekable<I> {
1898     type Item = I::Item;
1899
1900     #[inline]
1901     fn next(&mut self) -> Option<I::Item> {
1902         match self.peeked.take() {
1903             Some(v) => v,
1904             None => self.iter.next(),
1905         }
1906     }
1907
1908     #[inline]
1909     #[rustc_inherit_overflow_checks]
1910     fn count(mut self) -> usize {
1911         match self.peeked.take() {
1912             Some(None) => 0,
1913             Some(Some(_)) => 1 + self.iter.count(),
1914             None => self.iter.count(),
1915         }
1916     }
1917
1918     #[inline]
1919     fn nth(&mut self, n: usize) -> Option<I::Item> {
1920         // FIXME(#43234): merge these when borrow-checking gets better.
1921         if n == 0 {
1922             match self.peeked.take() {
1923                 Some(v) => v,
1924                 None => self.iter.nth(n),
1925             }
1926         } else {
1927             match self.peeked.take() {
1928                 Some(None) => None,
1929                 Some(Some(_)) => self.iter.nth(n - 1),
1930                 None => self.iter.nth(n),
1931             }
1932         }
1933     }
1934
1935     #[inline]
1936     fn last(mut self) -> Option<I::Item> {
1937         let peek_opt = match self.peeked.take() {
1938             Some(None) => return None,
1939             Some(v) => v,
1940             None => None,
1941         };
1942         self.iter.last().or(peek_opt)
1943     }
1944
1945     #[inline]
1946     fn size_hint(&self) -> (usize, Option<usize>) {
1947         let peek_len = match self.peeked {
1948             Some(None) => return (0, Some(0)),
1949             Some(Some(_)) => 1,
1950             None => 0,
1951         };
1952         let (lo, hi) = self.iter.size_hint();
1953         let lo = lo.saturating_add(peek_len);
1954         let hi = hi.and_then(|x| x.checked_add(peek_len));
1955         (lo, hi)
1956     }
1957
1958     #[inline]
1959     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1960         Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1961     {
1962         let acc = match self.peeked.take() {
1963             Some(None) => return Try::from_ok(init),
1964             Some(Some(v)) => f(init, v)?,
1965             None => init,
1966         };
1967         self.iter.try_fold(acc, f)
1968     }
1969
1970     #[inline]
1971     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1972         where Fold: FnMut(Acc, Self::Item) -> Acc,
1973     {
1974         let acc = match self.peeked {
1975             Some(None) => return init,
1976             Some(Some(v)) => fold(init, v),
1977             None => init,
1978         };
1979         self.iter.fold(acc, fold)
1980     }
1981 }
1982
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1985
1986 #[stable(feature = "fused", since = "1.26.0")]
1987 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1988
1989 impl<I: Iterator> Peekable<I> {
1990     /// Returns a reference to the next() value without advancing the iterator.
1991     ///
1992     /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1993     /// But if the iteration is over, `None` is returned.
1994     ///
1995     /// [`next`]: trait.Iterator.html#tymethod.next
1996     ///
1997     /// Because `peek()` returns a reference, and many iterators iterate over
1998     /// references, there can be a possibly confusing situation where the
1999     /// return value is a double reference. You can see this effect in the
2000     /// examples below.
2001     ///
2002     /// # Examples
2003     ///
2004     /// Basic usage:
2005     ///
2006     /// ```
2007     /// let xs = [1, 2, 3];
2008     ///
2009     /// let mut iter = xs.iter().peekable();
2010     ///
2011     /// // peek() lets us see into the future
2012     /// assert_eq!(iter.peek(), Some(&&1));
2013     /// assert_eq!(iter.next(), Some(&1));
2014     ///
2015     /// assert_eq!(iter.next(), Some(&2));
2016     ///
2017     /// // The iterator does not advance even if we `peek` multiple times
2018     /// assert_eq!(iter.peek(), Some(&&3));
2019     /// assert_eq!(iter.peek(), Some(&&3));
2020     ///
2021     /// assert_eq!(iter.next(), Some(&3));
2022     ///
2023     /// // After the iterator is finished, so is `peek()`
2024     /// assert_eq!(iter.peek(), None);
2025     /// assert_eq!(iter.next(), None);
2026     /// ```
2027     #[inline]
2028     #[stable(feature = "rust1", since = "1.0.0")]
2029     pub fn peek(&mut self) -> Option<&I::Item> {
2030         if self.peeked.is_none() {
2031             self.peeked = Some(self.iter.next());
2032         }
2033         match self.peeked {
2034             Some(Some(ref value)) => Some(value),
2035             Some(None) => None,
2036             _ => unreachable!(),
2037         }
2038     }
2039 }
2040
2041 /// An iterator that rejects elements while `predicate` is true.
2042 ///
2043 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
2044 /// documentation for more.
2045 ///
2046 /// [`skip_while`]: trait.Iterator.html#method.skip_while
2047 /// [`Iterator`]: trait.Iterator.html
2048 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2049 #[stable(feature = "rust1", since = "1.0.0")]
2050 #[derive(Clone)]
2051 pub struct SkipWhile<I, P> {
2052     iter: I,
2053     flag: bool,
2054     predicate: P,
2055 }
2056
2057 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2058 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
2059     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2060         f.debug_struct("SkipWhile")
2061             .field("iter", &self.iter)
2062             .field("flag", &self.flag)
2063             .finish()
2064     }
2065 }
2066
2067 #[stable(feature = "rust1", since = "1.0.0")]
2068 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
2069     where P: FnMut(&I::Item) -> bool
2070 {
2071     type Item = I::Item;
2072
2073     #[inline]
2074     fn next(&mut self) -> Option<I::Item> {
2075         let flag = &mut self.flag;
2076         let pred = &mut self.predicate;
2077         self.iter.find(move |x| {
2078             if *flag || !pred(x) {
2079                 *flag = true;
2080                 true
2081             } else {
2082                 false
2083             }
2084         })
2085     }
2086
2087     #[inline]
2088     fn size_hint(&self) -> (usize, Option<usize>) {
2089         let (_, upper) = self.iter.size_hint();
2090         (0, upper) // can't know a lower bound, due to the predicate
2091     }
2092
2093     #[inline]
2094     fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2095         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2096     {
2097         if !self.flag {
2098             match self.next() {
2099                 Some(v) => init = fold(init, v)?,
2100                 None => return Try::from_ok(init),
2101             }
2102         }
2103         self.iter.try_fold(init, fold)
2104     }
2105
2106     #[inline]
2107     fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
2108         where Fold: FnMut(Acc, Self::Item) -> Acc,
2109     {
2110         if !self.flag {
2111             match self.next() {
2112                 Some(v) => init = fold(init, v),
2113                 None => return init,
2114             }
2115         }
2116         self.iter.fold(init, fold)
2117     }
2118 }
2119
2120 #[stable(feature = "fused", since = "1.26.0")]
2121 impl<I, P> FusedIterator for SkipWhile<I, P>
2122     where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
2123
2124 /// An iterator that only accepts elements while `predicate` is true.
2125 ///
2126 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
2127 /// documentation for more.
2128 ///
2129 /// [`take_while`]: trait.Iterator.html#method.take_while
2130 /// [`Iterator`]: trait.Iterator.html
2131 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 #[derive(Clone)]
2134 pub struct TakeWhile<I, P> {
2135     iter: I,
2136     flag: bool,
2137     predicate: P,
2138 }
2139
2140 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2141 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
2142     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2143         f.debug_struct("TakeWhile")
2144             .field("iter", &self.iter)
2145             .field("flag", &self.flag)
2146             .finish()
2147     }
2148 }
2149
2150 #[stable(feature = "rust1", since = "1.0.0")]
2151 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2152     where P: FnMut(&I::Item) -> bool
2153 {
2154     type Item = I::Item;
2155
2156     #[inline]
2157     fn next(&mut self) -> Option<I::Item> {
2158         if self.flag {
2159             None
2160         } else {
2161             self.iter.next().and_then(|x| {
2162                 if (self.predicate)(&x) {
2163                     Some(x)
2164                 } else {
2165                     self.flag = true;
2166                     None
2167                 }
2168             })
2169         }
2170     }
2171
2172     #[inline]
2173     fn size_hint(&self) -> (usize, Option<usize>) {
2174         let (_, upper) = self.iter.size_hint();
2175         (0, upper) // can't know a lower bound, due to the predicate
2176     }
2177
2178     #[inline]
2179     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2180         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2181     {
2182         if self.flag {
2183             Try::from_ok(init)
2184         } else {
2185             let flag = &mut self.flag;
2186             let p = &mut self.predicate;
2187             self.iter.try_fold(init, move |acc, x|{
2188                 if p(&x) {
2189                     LoopState::from_try(fold(acc, x))
2190                 } else {
2191                     *flag = true;
2192                     LoopState::Break(Try::from_ok(acc))
2193                 }
2194             }).into_try()
2195         }
2196     }
2197 }
2198
2199 #[stable(feature = "fused", since = "1.26.0")]
2200 impl<I, P> FusedIterator for TakeWhile<I, P>
2201     where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
2202
2203 /// An iterator that skips over `n` elements of `iter`.
2204 ///
2205 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
2206 /// documentation for more.
2207 ///
2208 /// [`skip`]: trait.Iterator.html#method.skip
2209 /// [`Iterator`]: trait.Iterator.html
2210 #[derive(Clone, Debug)]
2211 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2212 #[stable(feature = "rust1", since = "1.0.0")]
2213 pub struct Skip<I> {
2214     iter: I,
2215     n: usize
2216 }
2217
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 impl<I> Iterator for Skip<I> where I: Iterator {
2220     type Item = <I as Iterator>::Item;
2221
2222     #[inline]
2223     fn next(&mut self) -> Option<I::Item> {
2224         if self.n == 0 {
2225             self.iter.next()
2226         } else {
2227             let old_n = self.n;
2228             self.n = 0;
2229             self.iter.nth(old_n)
2230         }
2231     }
2232
2233     #[inline]
2234     fn nth(&mut self, n: usize) -> Option<I::Item> {
2235         // Can't just add n + self.n due to overflow.
2236         if self.n == 0 {
2237             self.iter.nth(n)
2238         } else {
2239             let to_skip = self.n;
2240             self.n = 0;
2241             // nth(n) skips n+1
2242             if self.iter.nth(to_skip-1).is_none() {
2243                 return None;
2244             }
2245             self.iter.nth(n)
2246         }
2247     }
2248
2249     #[inline]
2250     fn count(self) -> usize {
2251         self.iter.count().saturating_sub(self.n)
2252     }
2253
2254     #[inline]
2255     fn last(mut self) -> Option<I::Item> {
2256         if self.n == 0 {
2257             self.iter.last()
2258         } else {
2259             let next = self.next();
2260             if next.is_some() {
2261                 // recurse. n should be 0.
2262                 self.last().or(next)
2263             } else {
2264                 None
2265             }
2266         }
2267     }
2268
2269     #[inline]
2270     fn size_hint(&self) -> (usize, Option<usize>) {
2271         let (lower, upper) = self.iter.size_hint();
2272
2273         let lower = lower.saturating_sub(self.n);
2274         let upper = upper.map(|x| x.saturating_sub(self.n));
2275
2276         (lower, upper)
2277     }
2278
2279     #[inline]
2280     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2281         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2282     {
2283         let n = self.n;
2284         self.n = 0;
2285         if n > 0 {
2286             // nth(n) skips n+1
2287             if self.iter.nth(n - 1).is_none() {
2288                 return Try::from_ok(init);
2289             }
2290         }
2291         self.iter.try_fold(init, fold)
2292     }
2293
2294     #[inline]
2295     fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2296         where Fold: FnMut(Acc, Self::Item) -> Acc,
2297     {
2298         if self.n > 0 {
2299             // nth(n) skips n+1
2300             if self.iter.nth(self.n - 1).is_none() {
2301                 return init;
2302             }
2303         }
2304         self.iter.fold(init, fold)
2305     }
2306 }
2307
2308 #[stable(feature = "rust1", since = "1.0.0")]
2309 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2310
2311 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
2312 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
2313     fn next_back(&mut self) -> Option<Self::Item> {
2314         if self.len() > 0 {
2315             self.iter.next_back()
2316         } else {
2317             None
2318         }
2319     }
2320
2321     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2322         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2323     {
2324         let mut n = self.len();
2325         if n == 0 {
2326             Try::from_ok(init)
2327         } else {
2328             self.iter.try_rfold(init, move |acc, x| {
2329                 n -= 1;
2330                 let r = fold(acc, x);
2331                 if n == 0 { LoopState::Break(r) }
2332                 else { LoopState::from_try(r) }
2333             }).into_try()
2334         }
2335     }
2336 }
2337
2338 #[stable(feature = "fused", since = "1.26.0")]
2339 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2340
2341 /// An iterator that only iterates over the first `n` iterations of `iter`.
2342 ///
2343 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2344 /// documentation for more.
2345 ///
2346 /// [`take`]: trait.Iterator.html#method.take
2347 /// [`Iterator`]: trait.Iterator.html
2348 #[derive(Clone, Debug)]
2349 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2350 #[stable(feature = "rust1", since = "1.0.0")]
2351 pub struct Take<I> {
2352     iter: I,
2353     n: usize
2354 }
2355
2356 #[stable(feature = "rust1", since = "1.0.0")]
2357 impl<I> Iterator for Take<I> where I: Iterator{
2358     type Item = <I as Iterator>::Item;
2359
2360     #[inline]
2361     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2362         if self.n != 0 {
2363             self.n -= 1;
2364             self.iter.next()
2365         } else {
2366             None
2367         }
2368     }
2369
2370     #[inline]
2371     fn nth(&mut self, n: usize) -> Option<I::Item> {
2372         if self.n > n {
2373             self.n -= n + 1;
2374             self.iter.nth(n)
2375         } else {
2376             if self.n > 0 {
2377                 self.iter.nth(self.n - 1);
2378                 self.n = 0;
2379             }
2380             None
2381         }
2382     }
2383
2384     #[inline]
2385     fn size_hint(&self) -> (usize, Option<usize>) {
2386         let (lower, upper) = self.iter.size_hint();
2387
2388         let lower = cmp::min(lower, self.n);
2389
2390         let upper = match upper {
2391             Some(x) if x < self.n => Some(x),
2392             _ => Some(self.n)
2393         };
2394
2395         (lower, upper)
2396     }
2397
2398     #[inline]
2399     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2400         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2401     {
2402         if self.n == 0 {
2403             Try::from_ok(init)
2404         } else {
2405             let n = &mut self.n;
2406             self.iter.try_fold(init, move |acc, x| {
2407                 *n -= 1;
2408                 let r = fold(acc, x);
2409                 if *n == 0 { LoopState::Break(r) }
2410                 else { LoopState::from_try(r) }
2411             }).into_try()
2412         }
2413     }
2414 }
2415
2416 #[stable(feature = "rust1", since = "1.0.0")]
2417 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2418
2419 #[stable(feature = "fused", since = "1.26.0")]
2420 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2421
2422 #[unstable(feature = "trusted_len", issue = "37572")]
2423 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2424
2425 /// An iterator to maintain state while iterating another iterator.
2426 ///
2427 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2428 /// documentation for more.
2429 ///
2430 /// [`scan`]: trait.Iterator.html#method.scan
2431 /// [`Iterator`]: trait.Iterator.html
2432 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 #[derive(Clone)]
2435 pub struct Scan<I, St, F> {
2436     iter: I,
2437     f: F,
2438     state: St,
2439 }
2440
2441 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2442 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2443     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2444         f.debug_struct("Scan")
2445             .field("iter", &self.iter)
2446             .field("state", &self.state)
2447             .finish()
2448     }
2449 }
2450
2451 #[stable(feature = "rust1", since = "1.0.0")]
2452 impl<B, I, St, F> Iterator for Scan<I, St, F> where
2453     I: Iterator,
2454     F: FnMut(&mut St, I::Item) -> Option<B>,
2455 {
2456     type Item = B;
2457
2458     #[inline]
2459     fn next(&mut self) -> Option<B> {
2460         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2461     }
2462
2463     #[inline]
2464     fn size_hint(&self) -> (usize, Option<usize>) {
2465         let (_, upper) = self.iter.size_hint();
2466         (0, upper) // can't know a lower bound, due to the scan function
2467     }
2468
2469     #[inline]
2470     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2471         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2472     {
2473         let state = &mut self.state;
2474         let f = &mut self.f;
2475         self.iter.try_fold(init, move |acc, x| {
2476             match f(state, x) {
2477                 None => LoopState::Break(Try::from_ok(acc)),
2478                 Some(x) => LoopState::from_try(fold(acc, x)),
2479             }
2480         }).into_try()
2481     }
2482 }
2483
2484 /// An iterator that maps each element to an iterator, and yields the elements
2485 /// of the produced iterators.
2486 ///
2487 /// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
2488 /// documentation for more.
2489 ///
2490 /// [`flat_map`]: trait.Iterator.html#method.flat_map
2491 /// [`Iterator`]: trait.Iterator.html
2492 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2493 #[stable(feature = "rust1", since = "1.0.0")]
2494 pub struct FlatMap<I, U: IntoIterator, F> {
2495     inner: FlattenCompat<Map<I, F>, <U as IntoIterator>::IntoIter>
2496 }
2497
2498 #[stable(feature = "rust1", since = "1.0.0")]
2499 impl<I: Clone, U: Clone + IntoIterator, F: Clone> Clone for FlatMap<I, U, F>
2500     where <U as IntoIterator>::IntoIter: Clone
2501 {
2502     fn clone(&self) -> Self { FlatMap { inner: self.inner.clone() } }
2503 }
2504
2505 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2506 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
2507     where U::IntoIter: fmt::Debug
2508 {
2509     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2510         f.debug_struct("FlatMap").field("inner", &self.inner).finish()
2511     }
2512 }
2513
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
2516     where F: FnMut(I::Item) -> U,
2517 {
2518     type Item = U::Item;
2519
2520     #[inline]
2521     fn next(&mut self) -> Option<U::Item> { self.inner.next() }
2522
2523     #[inline]
2524     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
2525
2526     #[inline]
2527     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2528         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2529     {
2530         self.inner.try_fold(init, fold)
2531     }
2532
2533     #[inline]
2534     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2535         where Fold: FnMut(Acc, Self::Item) -> Acc,
2536     {
2537         self.inner.fold(init, fold)
2538     }
2539 }
2540
2541 #[stable(feature = "rust1", since = "1.0.0")]
2542 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F>
2543     where F: FnMut(I::Item) -> U,
2544           U: IntoIterator,
2545           U::IntoIter: DoubleEndedIterator
2546 {
2547     #[inline]
2548     fn next_back(&mut self) -> Option<U::Item> { self.inner.next_back() }
2549
2550     #[inline]
2551     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2552         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2553     {
2554         self.inner.try_rfold(init, fold)
2555     }
2556
2557     #[inline]
2558     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2559         where Fold: FnMut(Acc, Self::Item) -> Acc,
2560     {
2561         self.inner.rfold(init, fold)
2562     }
2563 }
2564
2565 #[stable(feature = "fused", since = "1.26.0")]
2566 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
2567     where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
2568
2569 /// An iterator that flattens one level of nesting in an iterator of things
2570 /// that can be turned into iterators.
2571 ///
2572 /// This `struct` is created by the [`flatten`] method on [`Iterator`]. See its
2573 /// documentation for more.
2574 ///
2575 /// [`flatten`]: trait.Iterator.html#method.flatten
2576 /// [`Iterator`]: trait.Iterator.html
2577 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2578 #[stable(feature = "iterator_flatten", since = "1.29")]
2579 pub struct Flatten<I: Iterator>
2580 where I::Item: IntoIterator {
2581     inner: FlattenCompat<I, <I::Item as IntoIterator>::IntoIter>,
2582 }
2583
2584 #[stable(feature = "iterator_flatten", since = "1.29")]
2585 impl<I, U> fmt::Debug for Flatten<I>
2586     where I: Iterator + fmt::Debug, U: Iterator + fmt::Debug,
2587           I::Item: IntoIterator<IntoIter = U, Item = U::Item>,
2588 {
2589     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2590         f.debug_struct("Flatten").field("inner", &self.inner).finish()
2591     }
2592 }
2593
2594 #[stable(feature = "iterator_flatten", since = "1.29")]
2595 impl<I, U> Clone for Flatten<I>
2596     where I: Iterator + Clone, U: Iterator + Clone,
2597           I::Item: IntoIterator<IntoIter = U, Item = U::Item>,
2598 {
2599     fn clone(&self) -> Self { Flatten { inner: self.inner.clone() } }
2600 }
2601
2602 #[stable(feature = "iterator_flatten", since = "1.29")]
2603 impl<I, U> Iterator for Flatten<I>
2604     where I: Iterator, U: Iterator,
2605           I::Item: IntoIterator<IntoIter = U, Item = U::Item>
2606 {
2607     type Item = U::Item;
2608
2609     #[inline]
2610     fn next(&mut self) -> Option<U::Item> { self.inner.next() }
2611
2612     #[inline]
2613     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
2614
2615     #[inline]
2616     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2617         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2618     {
2619         self.inner.try_fold(init, fold)
2620     }
2621
2622     #[inline]
2623     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2624         where Fold: FnMut(Acc, Self::Item) -> Acc,
2625     {
2626         self.inner.fold(init, fold)
2627     }
2628 }
2629
2630 #[stable(feature = "iterator_flatten", since = "1.29")]
2631 impl<I, U> DoubleEndedIterator for Flatten<I>
2632     where I: DoubleEndedIterator, U: DoubleEndedIterator,
2633           I::Item: IntoIterator<IntoIter = U, Item = U::Item>
2634 {
2635     #[inline]
2636     fn next_back(&mut self) -> Option<U::Item> { self.inner.next_back() }
2637
2638     #[inline]
2639     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2640         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2641     {
2642         self.inner.try_rfold(init, fold)
2643     }
2644
2645     #[inline]
2646     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2647         where Fold: FnMut(Acc, Self::Item) -> Acc,
2648     {
2649         self.inner.rfold(init, fold)
2650     }
2651 }
2652
2653 #[stable(feature = "iterator_flatten", since = "1.29")]
2654 impl<I, U> FusedIterator for Flatten<I>
2655     where I: FusedIterator, U: Iterator,
2656           I::Item: IntoIterator<IntoIter = U, Item = U::Item> {}
2657
2658 /// Adapts an iterator by flattening it, for use in `flatten()` and `flat_map()`.
2659 fn flatten_compat<I, U>(iter: I) -> FlattenCompat<I, U> {
2660     FlattenCompat { iter, frontiter: None, backiter: None }
2661 }
2662
2663 /// Real logic of both `Flatten` and `FlatMap` which simply delegate to
2664 /// this type.
2665 #[derive(Clone, Debug)]
2666 struct FlattenCompat<I, U> {
2667     iter: I,
2668     frontiter: Option<U>,
2669     backiter: Option<U>,
2670 }
2671
2672 impl<I, U> Iterator for FlattenCompat<I, U>
2673     where I: Iterator, U: Iterator,
2674           I::Item: IntoIterator<IntoIter = U, Item = U::Item>
2675 {
2676     type Item = U::Item;
2677
2678     #[inline]
2679     fn next(&mut self) -> Option<U::Item> {
2680         loop {
2681             if let Some(ref mut inner) = self.frontiter {
2682                 if let elt@Some(_) = inner.next() { return elt }
2683             }
2684             match self.iter.next() {
2685                 None => return self.backiter.as_mut().and_then(|it| it.next()),
2686                 Some(inner) => self.frontiter = Some(inner.into_iter()),
2687             }
2688         }
2689     }
2690
2691     #[inline]
2692     fn size_hint(&self) -> (usize, Option<usize>) {
2693         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2694         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2695         let lo = flo.saturating_add(blo);
2696         match (self.iter.size_hint(), fhi, bhi) {
2697             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2698             _ => (lo, None)
2699         }
2700     }
2701
2702     #[inline]
2703     fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2704         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2705     {
2706         if let Some(ref mut front) = self.frontiter {
2707             init = front.try_fold(init, &mut fold)?;
2708         }
2709         self.frontiter = None;
2710
2711         {
2712             let frontiter = &mut self.frontiter;
2713             init = self.iter.try_fold(init, |acc, x| {
2714                 let mut mid = x.into_iter();
2715                 let r = mid.try_fold(acc, &mut fold);
2716                 *frontiter = Some(mid);
2717                 r
2718             })?;
2719         }
2720         self.frontiter = None;
2721
2722         if let Some(ref mut back) = self.backiter {
2723             init = back.try_fold(init, &mut fold)?;
2724         }
2725         self.backiter = None;
2726
2727         Try::from_ok(init)
2728     }
2729
2730     #[inline]
2731     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2732         where Fold: FnMut(Acc, Self::Item) -> Acc,
2733     {
2734         self.frontiter.into_iter()
2735             .chain(self.iter.map(IntoIterator::into_iter))
2736             .chain(self.backiter)
2737             .fold(init, |acc, iter| iter.fold(acc, &mut fold))
2738     }
2739 }
2740
2741 impl<I, U> DoubleEndedIterator for FlattenCompat<I, U>
2742     where I: DoubleEndedIterator, U: DoubleEndedIterator,
2743           I::Item: IntoIterator<IntoIter = U, Item = U::Item>
2744 {
2745     #[inline]
2746     fn next_back(&mut self) -> Option<U::Item> {
2747         loop {
2748             if let Some(ref mut inner) = self.backiter {
2749                 if let elt@Some(_) = inner.next_back() { return elt }
2750             }
2751             match self.iter.next_back() {
2752                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2753                 next => self.backiter = next.map(IntoIterator::into_iter),
2754             }
2755         }
2756     }
2757
2758     #[inline]
2759     fn try_rfold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2760         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2761     {
2762         if let Some(ref mut back) = self.backiter {
2763             init = back.try_rfold(init, &mut fold)?;
2764         }
2765         self.backiter = None;
2766
2767         {
2768             let backiter = &mut self.backiter;
2769             init = self.iter.try_rfold(init, |acc, x| {
2770                 let mut mid = x.into_iter();
2771                 let r = mid.try_rfold(acc, &mut fold);
2772                 *backiter = Some(mid);
2773                 r
2774             })?;
2775         }
2776         self.backiter = None;
2777
2778         if let Some(ref mut front) = self.frontiter {
2779             init = front.try_rfold(init, &mut fold)?;
2780         }
2781         self.frontiter = None;
2782
2783         Try::from_ok(init)
2784     }
2785
2786     #[inline]
2787     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2788         where Fold: FnMut(Acc, Self::Item) -> Acc,
2789     {
2790         self.frontiter.into_iter()
2791             .chain(self.iter.map(IntoIterator::into_iter))
2792             .chain(self.backiter)
2793             .rfold(init, |acc, iter| iter.rfold(acc, &mut fold))
2794     }
2795 }
2796
2797 /// An iterator that yields `None` forever after the underlying iterator
2798 /// yields `None` once.
2799 ///
2800 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
2801 /// documentation for more.
2802 ///
2803 /// [`fuse`]: trait.Iterator.html#method.fuse
2804 /// [`Iterator`]: trait.Iterator.html
2805 #[derive(Clone, Debug)]
2806 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2807 #[stable(feature = "rust1", since = "1.0.0")]
2808 pub struct Fuse<I> {
2809     iter: I,
2810     done: bool
2811 }
2812
2813 #[stable(feature = "fused", since = "1.26.0")]
2814 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
2815
2816 #[stable(feature = "rust1", since = "1.0.0")]
2817 impl<I> Iterator for Fuse<I> where I: Iterator {
2818     type Item = <I as Iterator>::Item;
2819
2820     #[inline]
2821     default fn next(&mut self) -> Option<<I as Iterator>::Item> {
2822         if self.done {
2823             None
2824         } else {
2825             let next = self.iter.next();
2826             self.done = next.is_none();
2827             next
2828         }
2829     }
2830
2831     #[inline]
2832     default fn nth(&mut self, n: usize) -> Option<I::Item> {
2833         if self.done {
2834             None
2835         } else {
2836             let nth = self.iter.nth(n);
2837             self.done = nth.is_none();
2838             nth
2839         }
2840     }
2841
2842     #[inline]
2843     default fn last(self) -> Option<I::Item> {
2844         if self.done {
2845             None
2846         } else {
2847             self.iter.last()
2848         }
2849     }
2850
2851     #[inline]
2852     default fn count(self) -> usize {
2853         if self.done {
2854             0
2855         } else {
2856             self.iter.count()
2857         }
2858     }
2859
2860     #[inline]
2861     default fn size_hint(&self) -> (usize, Option<usize>) {
2862         if self.done {
2863             (0, Some(0))
2864         } else {
2865             self.iter.size_hint()
2866         }
2867     }
2868
2869     #[inline]
2870     default fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2871         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2872     {
2873         if self.done {
2874             Try::from_ok(init)
2875         } else {
2876             let acc = self.iter.try_fold(init, fold)?;
2877             self.done = true;
2878             Try::from_ok(acc)
2879         }
2880     }
2881
2882     #[inline]
2883     default fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2884         where Fold: FnMut(Acc, Self::Item) -> Acc,
2885     {
2886         if self.done {
2887             init
2888         } else {
2889             self.iter.fold(init, fold)
2890         }
2891     }
2892 }
2893
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2896     #[inline]
2897     default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2898         if self.done {
2899             None
2900         } else {
2901             let next = self.iter.next_back();
2902             self.done = next.is_none();
2903             next
2904         }
2905     }
2906
2907     #[inline]
2908     default fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2909         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2910     {
2911         if self.done {
2912             Try::from_ok(init)
2913         } else {
2914             let acc = self.iter.try_rfold(init, fold)?;
2915             self.done = true;
2916             Try::from_ok(acc)
2917         }
2918     }
2919
2920     #[inline]
2921     default fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2922         where Fold: FnMut(Acc, Self::Item) -> Acc,
2923     {
2924         if self.done {
2925             init
2926         } else {
2927             self.iter.rfold(init, fold)
2928         }
2929     }
2930 }
2931
2932 unsafe impl<I> TrustedRandomAccess for Fuse<I>
2933     where I: TrustedRandomAccess,
2934 {
2935     unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
2936         self.iter.get_unchecked(i)
2937     }
2938
2939     fn may_have_side_effect() -> bool {
2940         I::may_have_side_effect()
2941     }
2942 }
2943
2944 #[stable(feature = "fused", since = "1.26.0")]
2945 impl<I> Iterator for Fuse<I> where I: FusedIterator {
2946     #[inline]
2947     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2948         self.iter.next()
2949     }
2950
2951     #[inline]
2952     fn nth(&mut self, n: usize) -> Option<I::Item> {
2953         self.iter.nth(n)
2954     }
2955
2956     #[inline]
2957     fn last(self) -> Option<I::Item> {
2958         self.iter.last()
2959     }
2960
2961     #[inline]
2962     fn count(self) -> usize {
2963         self.iter.count()
2964     }
2965
2966     #[inline]
2967     fn size_hint(&self) -> (usize, Option<usize>) {
2968         self.iter.size_hint()
2969     }
2970
2971     #[inline]
2972     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2973         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2974     {
2975         self.iter.try_fold(init, fold)
2976     }
2977
2978     #[inline]
2979     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2980         where Fold: FnMut(Acc, Self::Item) -> Acc,
2981     {
2982         self.iter.fold(init, fold)
2983     }
2984 }
2985
2986 #[stable(feature = "fused", since = "1.26.0")]
2987 impl<I> DoubleEndedIterator for Fuse<I>
2988     where I: DoubleEndedIterator + FusedIterator
2989 {
2990     #[inline]
2991     fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2992         self.iter.next_back()
2993     }
2994
2995     #[inline]
2996     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2997         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2998     {
2999         self.iter.try_rfold(init, fold)
3000     }
3001
3002     #[inline]
3003     fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
3004         where Fold: FnMut(Acc, Self::Item) -> Acc,
3005     {
3006         self.iter.rfold(init, fold)
3007     }
3008 }
3009
3010
3011 #[stable(feature = "rust1", since = "1.0.0")]
3012 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
3013     fn len(&self) -> usize {
3014         self.iter.len()
3015     }
3016
3017     fn is_empty(&self) -> bool {
3018         self.iter.is_empty()
3019     }
3020 }
3021
3022 /// An iterator that calls a function with a reference to each element before
3023 /// yielding it.
3024 ///
3025 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
3026 /// documentation for more.
3027 ///
3028 /// [`inspect`]: trait.Iterator.html#method.inspect
3029 /// [`Iterator`]: trait.Iterator.html
3030 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3031 #[stable(feature = "rust1", since = "1.0.0")]
3032 #[derive(Clone)]
3033 pub struct Inspect<I, F> {
3034     iter: I,
3035     f: F,
3036 }
3037
3038 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3039 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
3040     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3041         f.debug_struct("Inspect")
3042             .field("iter", &self.iter)
3043             .finish()
3044     }
3045 }
3046
3047 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
3048     #[inline]
3049     fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
3050         if let Some(ref a) = elt {
3051             (self.f)(a);
3052         }
3053
3054         elt
3055     }
3056 }
3057
3058 #[stable(feature = "rust1", since = "1.0.0")]
3059 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
3060     type Item = I::Item;
3061
3062     #[inline]
3063     fn next(&mut self) -> Option<I::Item> {
3064         let next = self.iter.next();
3065         self.do_inspect(next)
3066     }
3067
3068     #[inline]
3069     fn size_hint(&self) -> (usize, Option<usize>) {
3070         self.iter.size_hint()
3071     }
3072
3073     #[inline]
3074     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
3075         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
3076     {
3077         let f = &mut self.f;
3078         self.iter.try_fold(init, move |acc, item| { f(&item); fold(acc, item) })
3079     }
3080
3081     #[inline]
3082     fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
3083         where Fold: FnMut(Acc, Self::Item) -> Acc,
3084     {
3085         let mut f = self.f;
3086         self.iter.fold(init, move |acc, item| { f(&item); fold(acc, item) })
3087     }
3088 }
3089
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
3092     where F: FnMut(&I::Item),
3093 {
3094     #[inline]
3095     fn next_back(&mut self) -> Option<I::Item> {
3096         let next = self.iter.next_back();
3097         self.do_inspect(next)
3098     }
3099
3100     #[inline]
3101     fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
3102         Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
3103     {
3104         let f = &mut self.f;
3105         self.iter.try_rfold(init, move |acc, item| { f(&item); fold(acc, item) })
3106     }
3107
3108     #[inline]
3109     fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
3110         where Fold: FnMut(Acc, Self::Item) -> Acc,
3111     {
3112         let mut f = self.f;
3113         self.iter.rfold(init, move |acc, item| { f(&item); fold(acc, item) })
3114     }
3115 }
3116
3117 #[stable(feature = "rust1", since = "1.0.0")]
3118 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
3119     where F: FnMut(&I::Item)
3120 {
3121     fn len(&self) -> usize {
3122         self.iter.len()
3123     }
3124
3125     fn is_empty(&self) -> bool {
3126         self.iter.is_empty()
3127     }
3128 }
3129
3130 #[stable(feature = "fused", since = "1.26.0")]
3131 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
3132     where F: FnMut(&I::Item) {}