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