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