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