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