]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/iterator.rs
Remove redundant field names in structs
[rust.git] / src / libcore / iter / iterator.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 use cmp::Ordering;
12 use ops::Try;
13
14 use super::LoopState;
15 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, Fuse};
16 use super::{Flatten, FlatMap, flatten_compat};
17 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
18 use super::{Zip, Sum, Product};
19 use super::{ChainState, FromIterator, ZipImpl};
20
21 fn _assert_is_object_safe(_: &dyn Iterator<Item=()>) {}
22
23 /// An interface for dealing with iterators.
24 ///
25 /// This is the main iterator trait. For more about the concept of iterators
26 /// generally, please see the [module-level documentation]. In particular, you
27 /// may want to know how to [implement `Iterator`][impl].
28 ///
29 /// [module-level documentation]: index.html
30 /// [impl]: index.html#implementing-iterator
31 #[stable(feature = "rust1", since = "1.0.0")]
32 #[rustc_on_unimplemented(
33     on(
34         _Self="&str",
35         label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
36     ),
37     label="`{Self}` is not an iterator; maybe try calling `.iter()` or a similar method"
38 )]
39 #[doc(spotlight)]
40 pub trait Iterator {
41     /// The type of the elements being iterated over.
42     #[stable(feature = "rust1", since = "1.0.0")]
43     type Item;
44
45     /// Advances the iterator and returns the next value.
46     ///
47     /// Returns [`None`] when iteration is finished. Individual iterator
48     /// implementations may choose to resume iteration, and so calling `next()`
49     /// again may or may not eventually start returning [`Some(Item)`] again at some
50     /// point.
51     ///
52     /// [`None`]: ../../std/option/enum.Option.html#variant.None
53     /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
54     ///
55     /// # Examples
56     ///
57     /// Basic usage:
58     ///
59     /// ```
60     /// let a = [1, 2, 3];
61     ///
62     /// let mut iter = a.iter();
63     ///
64     /// // A call to next() returns the next value...
65     /// assert_eq!(Some(&1), iter.next());
66     /// assert_eq!(Some(&2), iter.next());
67     /// assert_eq!(Some(&3), iter.next());
68     ///
69     /// // ... and then None once it's over.
70     /// assert_eq!(None, iter.next());
71     ///
72     /// // More calls may or may not return None. Here, they always will.
73     /// assert_eq!(None, iter.next());
74     /// assert_eq!(None, iter.next());
75     /// ```
76     #[stable(feature = "rust1", since = "1.0.0")]
77     fn next(&mut self) -> Option<Self::Item>;
78
79     /// Returns the bounds on the remaining length of the iterator.
80     ///
81     /// Specifically, `size_hint()` returns a tuple where the first element
82     /// is the lower bound, and the second element is the upper bound.
83     ///
84     /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
85     /// A [`None`] here means that either there is no known upper bound, or the
86     /// upper bound is larger than [`usize`].
87     ///
88     /// # Implementation notes
89     ///
90     /// It is not enforced that an iterator implementation yields the declared
91     /// number of elements. A buggy iterator may yield less than the lower bound
92     /// or more than the upper bound of elements.
93     ///
94     /// `size_hint()` is primarily intended to be used for optimizations such as
95     /// reserving space for the elements of the iterator, but must not be
96     /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
97     /// implementation of `size_hint()` should not lead to memory safety
98     /// violations.
99     ///
100     /// That said, the implementation should provide a correct estimation,
101     /// because otherwise it would be a violation of the trait's protocol.
102     ///
103     /// The default implementation returns `(0, None)` which is correct for any
104     /// iterator.
105     ///
106     /// [`usize`]: ../../std/primitive.usize.html
107     /// [`Option`]: ../../std/option/enum.Option.html
108     /// [`None`]: ../../std/option/enum.Option.html#variant.None
109     ///
110     /// # Examples
111     ///
112     /// Basic usage:
113     ///
114     /// ```
115     /// let a = [1, 2, 3];
116     /// let iter = a.iter();
117     ///
118     /// assert_eq!((3, Some(3)), iter.size_hint());
119     /// ```
120     ///
121     /// A more complex example:
122     ///
123     /// ```
124     /// // The even numbers from zero to ten.
125     /// let iter = (0..10).filter(|x| x % 2 == 0);
126     ///
127     /// // We might iterate from zero to ten times. Knowing that it's five
128     /// // exactly wouldn't be possible without executing filter().
129     /// assert_eq!((0, Some(10)), iter.size_hint());
130     ///
131     /// // Let's add five more numbers with chain()
132     /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
133     ///
134     /// // now both bounds are increased by five
135     /// assert_eq!((5, Some(15)), iter.size_hint());
136     /// ```
137     ///
138     /// Returning `None` for an upper bound:
139     ///
140     /// ```
141     /// // an infinite iterator has no upper bound
142     /// // and the maximum possible lower bound
143     /// let iter = 0..;
144     ///
145     /// assert_eq!((usize::max_value(), None), iter.size_hint());
146     /// ```
147     #[inline]
148     #[stable(feature = "rust1", since = "1.0.0")]
149     fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
150
151     /// Consumes the iterator, counting the number of iterations and returning it.
152     ///
153     /// This method will evaluate the iterator until its [`next`] returns
154     /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
155     /// times it called [`next`].
156     ///
157     /// [`next`]: #tymethod.next
158     /// [`None`]: ../../std/option/enum.Option.html#variant.None
159     ///
160     /// # Overflow Behavior
161     ///
162     /// The method does no guarding against overflows, so counting elements of
163     /// an iterator with more than [`usize::MAX`] elements either produces the
164     /// wrong result or panics. If debug assertions are enabled, a panic is
165     /// guaranteed.
166     ///
167     /// # Panics
168     ///
169     /// This function might panic if the iterator has more than [`usize::MAX`]
170     /// elements.
171     ///
172     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
173     ///
174     /// # Examples
175     ///
176     /// Basic usage:
177     ///
178     /// ```
179     /// let a = [1, 2, 3];
180     /// assert_eq!(a.iter().count(), 3);
181     ///
182     /// let a = [1, 2, 3, 4, 5];
183     /// assert_eq!(a.iter().count(), 5);
184     /// ```
185     #[inline]
186     #[rustc_inherit_overflow_checks]
187     #[stable(feature = "rust1", since = "1.0.0")]
188     fn count(self) -> usize where Self: Sized {
189         // Might overflow.
190         self.fold(0, |cnt, _| cnt + 1)
191     }
192
193     /// Consumes the iterator, returning the last element.
194     ///
195     /// This method will evaluate the iterator until it returns [`None`]. While
196     /// doing so, it keeps track of the current element. After [`None`] is
197     /// returned, `last()` will then return the last element it saw.
198     ///
199     /// [`None`]: ../../std/option/enum.Option.html#variant.None
200     ///
201     /// # Examples
202     ///
203     /// Basic usage:
204     ///
205     /// ```
206     /// let a = [1, 2, 3];
207     /// assert_eq!(a.iter().last(), Some(&3));
208     ///
209     /// let a = [1, 2, 3, 4, 5];
210     /// assert_eq!(a.iter().last(), Some(&5));
211     /// ```
212     #[inline]
213     #[stable(feature = "rust1", since = "1.0.0")]
214     fn last(self) -> Option<Self::Item> where Self: Sized {
215         let mut last = None;
216         for x in self { last = Some(x); }
217         last
218     }
219
220     /// Returns the `n`th element of the iterator.
221     ///
222     /// Like most indexing operations, the count starts from zero, so `nth(0)`
223     /// returns the first value, `nth(1)` the second, and so on.
224     ///
225     /// Note that all preceding elements, as well as the returned element, will be
226     /// consumed from the iterator. That means that the preceding elements will be
227     /// discarded, and also that calling `nth(0)` multiple times on the same iterator
228     /// will return different elements.
229     ///
230     /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
231     /// iterator.
232     ///
233     /// [`None`]: ../../std/option/enum.Option.html#variant.None
234     ///
235     /// # Examples
236     ///
237     /// Basic usage:
238     ///
239     /// ```
240     /// let a = [1, 2, 3];
241     /// assert_eq!(a.iter().nth(1), Some(&2));
242     /// ```
243     ///
244     /// Calling `nth()` multiple times doesn't rewind the iterator:
245     ///
246     /// ```
247     /// let a = [1, 2, 3];
248     ///
249     /// let mut iter = a.iter();
250     ///
251     /// assert_eq!(iter.nth(1), Some(&2));
252     /// assert_eq!(iter.nth(1), None);
253     /// ```
254     ///
255     /// Returning `None` if there are less than `n + 1` elements:
256     ///
257     /// ```
258     /// let a = [1, 2, 3];
259     /// assert_eq!(a.iter().nth(10), None);
260     /// ```
261     #[inline]
262     #[stable(feature = "rust1", since = "1.0.0")]
263     fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
264         for x in self {
265             if n == 0 { return Some(x) }
266             n -= 1;
267         }
268         None
269     }
270
271     /// Creates an iterator starting at the same point, but stepping by
272     /// the given amount at each iteration.
273     ///
274     /// Note 1: The first element of the iterator will always be returned,
275     /// regardless of the step given.
276     ///
277     /// Note 2: The time at which ignored elements are pulled is not fixed.
278     /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), â€¦`,
279     /// but is also free to behave like the sequence
280     /// `advance_n_and_return_first(step), advance_n_and_return_first(step), â€¦`
281     /// Which way is used may change for some iterators for performance reasons.
282     /// The second way will advance the iterator earlier and may consume more items.
283     ///
284     /// `advance_n_and_return_first` is the equivalent of:
285     /// ```
286     /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
287     /// where
288     ///     I: Iterator,
289     /// {
290     ///     let next = iter.next();
291     ///     if total_step > 1 {
292     ///         iter.nth(total_step-2);
293     ///     }
294     ///     next
295     /// }
296     /// ```
297     ///
298     /// # Panics
299     ///
300     /// The method will panic if the given step is `0`.
301     ///
302     /// # Examples
303     ///
304     /// Basic usage:
305     ///
306     /// ```
307     /// let a = [0, 1, 2, 3, 4, 5];
308     /// let mut iter = a.into_iter().step_by(2);
309     ///
310     /// assert_eq!(iter.next(), Some(&0));
311     /// assert_eq!(iter.next(), Some(&2));
312     /// assert_eq!(iter.next(), Some(&4));
313     /// assert_eq!(iter.next(), None);
314     /// ```
315     #[inline]
316     #[stable(feature = "iterator_step_by", since = "1.28.0")]
317     fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
318         assert!(step != 0);
319         StepBy{iter: self, step: step - 1, first_take: true}
320     }
321
322     /// Takes two iterators and creates a new iterator over both in sequence.
323     ///
324     /// `chain()` will return a new iterator which will first iterate over
325     /// values from the first iterator and then over values from the second
326     /// iterator.
327     ///
328     /// In other words, it links two iterators together, in a chain. ðŸ”—
329     ///
330     /// # Examples
331     ///
332     /// Basic usage:
333     ///
334     /// ```
335     /// let a1 = [1, 2, 3];
336     /// let a2 = [4, 5, 6];
337     ///
338     /// let mut iter = a1.iter().chain(a2.iter());
339     ///
340     /// assert_eq!(iter.next(), Some(&1));
341     /// assert_eq!(iter.next(), Some(&2));
342     /// assert_eq!(iter.next(), Some(&3));
343     /// assert_eq!(iter.next(), Some(&4));
344     /// assert_eq!(iter.next(), Some(&5));
345     /// assert_eq!(iter.next(), Some(&6));
346     /// assert_eq!(iter.next(), None);
347     /// ```
348     ///
349     /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
350     /// anything that can be converted into an [`Iterator`], not just an
351     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
352     /// [`IntoIterator`], and so can be passed to `chain()` directly:
353     ///
354     /// [`IntoIterator`]: trait.IntoIterator.html
355     /// [`Iterator`]: trait.Iterator.html
356     ///
357     /// ```
358     /// let s1 = &[1, 2, 3];
359     /// let s2 = &[4, 5, 6];
360     ///
361     /// let mut iter = s1.iter().chain(s2);
362     ///
363     /// assert_eq!(iter.next(), Some(&1));
364     /// assert_eq!(iter.next(), Some(&2));
365     /// assert_eq!(iter.next(), Some(&3));
366     /// assert_eq!(iter.next(), Some(&4));
367     /// assert_eq!(iter.next(), Some(&5));
368     /// assert_eq!(iter.next(), Some(&6));
369     /// assert_eq!(iter.next(), None);
370     /// ```
371     #[inline]
372     #[stable(feature = "rust1", since = "1.0.0")]
373     fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
374         Self: Sized, U: IntoIterator<Item=Self::Item>,
375     {
376         Chain{a: self, b: other.into_iter(), state: ChainState::Both}
377     }
378
379     /// 'Zips up' two iterators into a single iterator of pairs.
380     ///
381     /// `zip()` returns a new iterator that will iterate over two other
382     /// iterators, returning a tuple where the first element comes from the
383     /// first iterator, and the second element comes from the second iterator.
384     ///
385     /// In other words, it zips two iterators together, into a single one.
386     ///
387     /// If either iterator returns [`None`], [`next`] from the zipped iterator
388     /// will return [`None`]. If the first iterator returns [`None`], `zip` will
389     /// short-circuit and `next` will not be called on the second iterator.
390     ///
391     /// # Examples
392     ///
393     /// Basic usage:
394     ///
395     /// ```
396     /// let a1 = [1, 2, 3];
397     /// let a2 = [4, 5, 6];
398     ///
399     /// let mut iter = a1.iter().zip(a2.iter());
400     ///
401     /// assert_eq!(iter.next(), Some((&1, &4)));
402     /// assert_eq!(iter.next(), Some((&2, &5)));
403     /// assert_eq!(iter.next(), Some((&3, &6)));
404     /// assert_eq!(iter.next(), None);
405     /// ```
406     ///
407     /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
408     /// anything that can be converted into an [`Iterator`], not just an
409     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
410     /// [`IntoIterator`], and so can be passed to `zip()` directly:
411     ///
412     /// [`IntoIterator`]: trait.IntoIterator.html
413     /// [`Iterator`]: trait.Iterator.html
414     ///
415     /// ```
416     /// let s1 = &[1, 2, 3];
417     /// let s2 = &[4, 5, 6];
418     ///
419     /// let mut iter = s1.iter().zip(s2);
420     ///
421     /// assert_eq!(iter.next(), Some((&1, &4)));
422     /// assert_eq!(iter.next(), Some((&2, &5)));
423     /// assert_eq!(iter.next(), Some((&3, &6)));
424     /// assert_eq!(iter.next(), None);
425     /// ```
426     ///
427     /// `zip()` is often used to zip an infinite iterator to a finite one.
428     /// This works because the finite iterator will eventually return [`None`],
429     /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
430     ///
431     /// ```
432     /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
433     ///
434     /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
435     ///
436     /// assert_eq!((0, 'f'), enumerate[0]);
437     /// assert_eq!((0, 'f'), zipper[0]);
438     ///
439     /// assert_eq!((1, 'o'), enumerate[1]);
440     /// assert_eq!((1, 'o'), zipper[1]);
441     ///
442     /// assert_eq!((2, 'o'), enumerate[2]);
443     /// assert_eq!((2, 'o'), zipper[2]);
444     /// ```
445     ///
446     /// [`enumerate`]: trait.Iterator.html#method.enumerate
447     /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
448     /// [`None`]: ../../std/option/enum.Option.html#variant.None
449     #[inline]
450     #[stable(feature = "rust1", since = "1.0.0")]
451     fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
452         Self: Sized, U: IntoIterator
453     {
454         Zip::new(self, other.into_iter())
455     }
456
457     /// Takes a closure and creates an iterator which calls that closure on each
458     /// element.
459     ///
460     /// `map()` transforms one iterator into another, by means of its argument:
461     /// something that implements `FnMut`. It produces a new iterator which
462     /// calls this closure on each element of the original iterator.
463     ///
464     /// If you are good at thinking in types, you can think of `map()` like this:
465     /// If you have an iterator that gives you elements of some type `A`, and
466     /// you want an iterator of some other type `B`, you can use `map()`,
467     /// passing a closure that takes an `A` and returns a `B`.
468     ///
469     /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
470     /// lazy, it is best used when you're already working with other iterators.
471     /// If you're doing some sort of looping for a side effect, it's considered
472     /// more idiomatic to use [`for`] than `map()`.
473     ///
474     /// [`for`]: ../../book/first-edition/loops.html#for
475     ///
476     /// # Examples
477     ///
478     /// Basic usage:
479     ///
480     /// ```
481     /// let a = [1, 2, 3];
482     ///
483     /// let mut iter = a.into_iter().map(|x| 2 * x);
484     ///
485     /// assert_eq!(iter.next(), Some(2));
486     /// assert_eq!(iter.next(), Some(4));
487     /// assert_eq!(iter.next(), Some(6));
488     /// assert_eq!(iter.next(), None);
489     /// ```
490     ///
491     /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
492     ///
493     /// ```
494     /// # #![allow(unused_must_use)]
495     /// // don't do this:
496     /// (0..5).map(|x| println!("{}", x));
497     ///
498     /// // it won't even execute, as it is lazy. Rust will warn you about this.
499     ///
500     /// // Instead, use for:
501     /// for x in 0..5 {
502     ///     println!("{}", x);
503     /// }
504     /// ```
505     #[inline]
506     #[stable(feature = "rust1", since = "1.0.0")]
507     fn map<B, F>(self, f: F) -> Map<Self, F> where
508         Self: Sized, F: FnMut(Self::Item) -> B,
509     {
510         Map { iter: self, f }
511     }
512
513     /// Calls a closure on each element of an iterator.
514     ///
515     /// This is equivalent to using a [`for`] loop on the iterator, although
516     /// `break` and `continue` are not possible from a closure.  It's generally
517     /// more idiomatic to use a `for` loop, but `for_each` may be more legible
518     /// when processing items at the end of longer iterator chains.  In some
519     /// cases `for_each` may also be faster than a loop, because it will use
520     /// internal iteration on adaptors like `Chain`.
521     ///
522     /// [`for`]: ../../book/first-edition/loops.html#for
523     ///
524     /// # Examples
525     ///
526     /// Basic usage:
527     ///
528     /// ```
529     /// use std::sync::mpsc::channel;
530     ///
531     /// let (tx, rx) = channel();
532     /// (0..5).map(|x| x * 2 + 1)
533     ///       .for_each(move |x| tx.send(x).unwrap());
534     ///
535     /// let v: Vec<_> =  rx.iter().collect();
536     /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
537     /// ```
538     ///
539     /// For such a small example, a `for` loop may be cleaner, but `for_each`
540     /// might be preferable to keep a functional style with longer iterators:
541     ///
542     /// ```
543     /// (0..5).flat_map(|x| x * 100 .. x * 110)
544     ///       .enumerate()
545     ///       .filter(|&(i, x)| (i + x) % 3 == 0)
546     ///       .for_each(|(i, x)| println!("{}:{}", i, x));
547     /// ```
548     #[inline]
549     #[stable(feature = "iterator_for_each", since = "1.21.0")]
550     fn for_each<F>(self, mut f: F) where
551         Self: Sized, F: FnMut(Self::Item),
552     {
553         self.fold((), move |(), item| f(item));
554     }
555
556     /// Creates an iterator which uses a closure to determine if an element
557     /// should be yielded.
558     ///
559     /// The closure must return `true` or `false`. `filter()` creates an
560     /// iterator which calls this closure on each element. If the closure
561     /// returns `true`, then the element is returned. If the closure returns
562     /// `false`, it will try again, and call the closure on the next element,
563     /// seeing if it passes the test.
564     ///
565     /// # Examples
566     ///
567     /// Basic usage:
568     ///
569     /// ```
570     /// let a = [0i32, 1, 2];
571     ///
572     /// let mut iter = a.into_iter().filter(|x| x.is_positive());
573     ///
574     /// assert_eq!(iter.next(), Some(&1));
575     /// assert_eq!(iter.next(), Some(&2));
576     /// assert_eq!(iter.next(), None);
577     /// ```
578     ///
579     /// Because the closure passed to `filter()` takes a reference, and many
580     /// iterators iterate over references, this leads to a possibly confusing
581     /// situation, where the type of the closure is a double reference:
582     ///
583     /// ```
584     /// let a = [0, 1, 2];
585     ///
586     /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
587     ///
588     /// assert_eq!(iter.next(), Some(&2));
589     /// assert_eq!(iter.next(), None);
590     /// ```
591     ///
592     /// It's common to instead use destructuring on the argument to strip away
593     /// one:
594     ///
595     /// ```
596     /// let a = [0, 1, 2];
597     ///
598     /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
599     ///
600     /// assert_eq!(iter.next(), Some(&2));
601     /// assert_eq!(iter.next(), None);
602     /// ```
603     ///
604     /// or both:
605     ///
606     /// ```
607     /// let a = [0, 1, 2];
608     ///
609     /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
610     ///
611     /// assert_eq!(iter.next(), Some(&2));
612     /// assert_eq!(iter.next(), None);
613     /// ```
614     ///
615     /// of these layers.
616     #[inline]
617     #[stable(feature = "rust1", since = "1.0.0")]
618     fn filter<P>(self, predicate: P) -> Filter<Self, P> where
619         Self: Sized, P: FnMut(&Self::Item) -> bool,
620     {
621         Filter {iter: self, predicate }
622     }
623
624     /// Creates an iterator that both filters and maps.
625     ///
626     /// The closure must return an [`Option<T>`]. `filter_map` creates an
627     /// iterator which calls this closure on each element. If the closure
628     /// returns [`Some(element)`][`Some`], then that element is returned. If the
629     /// closure returns [`None`], it will try again, and call the closure on the
630     /// next element, seeing if it will return [`Some`].
631     ///
632     /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
633     /// part:
634     ///
635     /// [`filter`]: #method.filter
636     /// [`map`]: #method.map
637     ///
638     /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
639     ///
640     /// In other words, it removes the [`Option<T>`] layer automatically. If your
641     /// mapping is already returning an [`Option<T>`] and you want to skip over
642     /// [`None`]s, then `filter_map` is much, much nicer to use.
643     ///
644     /// # Examples
645     ///
646     /// Basic usage:
647     ///
648     /// ```
649     /// let a = ["1", "lol", "3", "NaN", "5"];
650     ///
651     /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
652     ///
653     /// assert_eq!(iter.next(), Some(1));
654     /// assert_eq!(iter.next(), Some(3));
655     /// assert_eq!(iter.next(), Some(5));
656     /// assert_eq!(iter.next(), None);
657     /// ```
658     ///
659     /// Here's the same example, but with [`filter`] and [`map`]:
660     ///
661     /// ```
662     /// let a = ["1", "lol", "3", "NaN", "5"];
663     /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
664     /// assert_eq!(iter.next(), Some(1));
665     /// assert_eq!(iter.next(), Some(3));
666     /// assert_eq!(iter.next(), Some(5));
667     /// assert_eq!(iter.next(), None);
668     /// ```
669     ///
670     /// [`Option<T>`]: ../../std/option/enum.Option.html
671     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
672     /// [`None`]: ../../std/option/enum.Option.html#variant.None
673     #[inline]
674     #[stable(feature = "rust1", since = "1.0.0")]
675     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
676         Self: Sized, F: FnMut(Self::Item) -> Option<B>,
677     {
678         FilterMap { iter: self, f }
679     }
680
681     /// Creates an iterator which gives the current iteration count as well as
682     /// the next value.
683     ///
684     /// The iterator returned yields pairs `(i, val)`, where `i` is the
685     /// current index of iteration and `val` is the value returned by the
686     /// iterator.
687     ///
688     /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
689     /// different sized integer, the [`zip`] function provides similar
690     /// functionality.
691     ///
692     /// # Overflow Behavior
693     ///
694     /// The method does no guarding against overflows, so enumerating more than
695     /// [`usize::MAX`] elements either produces the wrong result or panics. If
696     /// debug assertions are enabled, a panic is guaranteed.
697     ///
698     /// # Panics
699     ///
700     /// The returned iterator might panic if the to-be-returned index would
701     /// overflow a [`usize`].
702     ///
703     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
704     /// [`usize`]: ../../std/primitive.usize.html
705     /// [`zip`]: #method.zip
706     ///
707     /// # Examples
708     ///
709     /// ```
710     /// let a = ['a', 'b', 'c'];
711     ///
712     /// let mut iter = a.iter().enumerate();
713     ///
714     /// assert_eq!(iter.next(), Some((0, &'a')));
715     /// assert_eq!(iter.next(), Some((1, &'b')));
716     /// assert_eq!(iter.next(), Some((2, &'c')));
717     /// assert_eq!(iter.next(), None);
718     /// ```
719     #[inline]
720     #[stable(feature = "rust1", since = "1.0.0")]
721     fn enumerate(self) -> Enumerate<Self> where Self: Sized {
722         Enumerate { iter: self, count: 0 }
723     }
724
725     /// Creates an iterator which can use `peek` to look at the next element of
726     /// the iterator without consuming it.
727     ///
728     /// Adds a [`peek`] method to an iterator. See its documentation for
729     /// more information.
730     ///
731     /// Note that the underlying iterator is still advanced when [`peek`] is
732     /// called for the first time: In order to retrieve the next element,
733     /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
734     /// anything other than fetching the next value) of the [`next`] method
735     /// will occur.
736     ///
737     /// [`peek`]: struct.Peekable.html#method.peek
738     /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
739     ///
740     /// # Examples
741     ///
742     /// Basic usage:
743     ///
744     /// ```
745     /// let xs = [1, 2, 3];
746     ///
747     /// let mut iter = xs.iter().peekable();
748     ///
749     /// // peek() lets us see into the future
750     /// assert_eq!(iter.peek(), Some(&&1));
751     /// assert_eq!(iter.next(), Some(&1));
752     ///
753     /// assert_eq!(iter.next(), Some(&2));
754     ///
755     /// // we can peek() multiple times, the iterator won't advance
756     /// assert_eq!(iter.peek(), Some(&&3));
757     /// assert_eq!(iter.peek(), Some(&&3));
758     ///
759     /// assert_eq!(iter.next(), Some(&3));
760     ///
761     /// // after the iterator is finished, so is peek()
762     /// assert_eq!(iter.peek(), None);
763     /// assert_eq!(iter.next(), None);
764     /// ```
765     #[inline]
766     #[stable(feature = "rust1", since = "1.0.0")]
767     fn peekable(self) -> Peekable<Self> where Self: Sized {
768         Peekable{iter: self, peeked: None}
769     }
770
771     /// Creates an iterator that [`skip`]s elements based on a predicate.
772     ///
773     /// [`skip`]: #method.skip
774     ///
775     /// `skip_while()` takes a closure as an argument. It will call this
776     /// closure on each element of the iterator, and ignore elements
777     /// until it returns `false`.
778     ///
779     /// After `false` is returned, `skip_while()`'s job is over, and the
780     /// rest of the elements are yielded.
781     ///
782     /// # Examples
783     ///
784     /// Basic usage:
785     ///
786     /// ```
787     /// let a = [-1i32, 0, 1];
788     ///
789     /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
790     ///
791     /// assert_eq!(iter.next(), Some(&0));
792     /// assert_eq!(iter.next(), Some(&1));
793     /// assert_eq!(iter.next(), None);
794     /// ```
795     ///
796     /// Because the closure passed to `skip_while()` takes a reference, and many
797     /// iterators iterate over references, this leads to a possibly confusing
798     /// situation, where the type of the closure is a double reference:
799     ///
800     /// ```
801     /// let a = [-1, 0, 1];
802     ///
803     /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
804     ///
805     /// assert_eq!(iter.next(), Some(&0));
806     /// assert_eq!(iter.next(), Some(&1));
807     /// assert_eq!(iter.next(), None);
808     /// ```
809     ///
810     /// Stopping after an initial `false`:
811     ///
812     /// ```
813     /// let a = [-1, 0, 1, -2];
814     ///
815     /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
816     ///
817     /// assert_eq!(iter.next(), Some(&0));
818     /// assert_eq!(iter.next(), Some(&1));
819     ///
820     /// // while this would have been false, since we already got a false,
821     /// // skip_while() isn't used any more
822     /// assert_eq!(iter.next(), Some(&-2));
823     ///
824     /// assert_eq!(iter.next(), None);
825     /// ```
826     #[inline]
827     #[stable(feature = "rust1", since = "1.0.0")]
828     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
829         Self: Sized, P: FnMut(&Self::Item) -> bool,
830     {
831         SkipWhile { iter: self, flag: false, predicate }
832     }
833
834     /// Creates an iterator that yields elements based on a predicate.
835     ///
836     /// `take_while()` takes a closure as an argument. It will call this
837     /// closure on each element of the iterator, and yield elements
838     /// while it returns `true`.
839     ///
840     /// After `false` is returned, `take_while()`'s job is over, and the
841     /// rest of the elements are ignored.
842     ///
843     /// # Examples
844     ///
845     /// Basic usage:
846     ///
847     /// ```
848     /// let a = [-1i32, 0, 1];
849     ///
850     /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
851     ///
852     /// assert_eq!(iter.next(), Some(&-1));
853     /// assert_eq!(iter.next(), None);
854     /// ```
855     ///
856     /// Because the closure passed to `take_while()` takes a reference, and many
857     /// iterators iterate over references, this leads to a possibly confusing
858     /// situation, where the type of the closure is a double reference:
859     ///
860     /// ```
861     /// let a = [-1, 0, 1];
862     ///
863     /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
864     ///
865     /// assert_eq!(iter.next(), Some(&-1));
866     /// assert_eq!(iter.next(), None);
867     /// ```
868     ///
869     /// Stopping after an initial `false`:
870     ///
871     /// ```
872     /// let a = [-1, 0, 1, -2];
873     ///
874     /// let mut iter = a.into_iter().take_while(|x| **x < 0);
875     ///
876     /// assert_eq!(iter.next(), Some(&-1));
877     ///
878     /// // We have more elements that are less than zero, but since we already
879     /// // got a false, take_while() isn't used any more
880     /// assert_eq!(iter.next(), None);
881     /// ```
882     ///
883     /// Because `take_while()` needs to look at the value in order to see if it
884     /// should be included or not, consuming iterators will see that it is
885     /// removed:
886     ///
887     /// ```
888     /// let a = [1, 2, 3, 4];
889     /// let mut iter = a.into_iter();
890     ///
891     /// let result: Vec<i32> = iter.by_ref()
892     ///                            .take_while(|n| **n != 3)
893     ///                            .cloned()
894     ///                            .collect();
895     ///
896     /// assert_eq!(result, &[1, 2]);
897     ///
898     /// let result: Vec<i32> = iter.cloned().collect();
899     ///
900     /// assert_eq!(result, &[4]);
901     /// ```
902     ///
903     /// The `3` is no longer there, because it was consumed in order to see if
904     /// the iteration should stop, but wasn't placed back into the iterator or
905     /// some similar thing.
906     #[inline]
907     #[stable(feature = "rust1", since = "1.0.0")]
908     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
909         Self: Sized, P: FnMut(&Self::Item) -> bool,
910     {
911         TakeWhile { iter: self, flag: false, predicate }
912     }
913
914     /// Creates an iterator that skips the first `n` elements.
915     ///
916     /// After they have been consumed, the rest of the elements are yielded.
917     ///
918     /// # Examples
919     ///
920     /// Basic usage:
921     ///
922     /// ```
923     /// let a = [1, 2, 3];
924     ///
925     /// let mut iter = a.iter().skip(2);
926     ///
927     /// assert_eq!(iter.next(), Some(&3));
928     /// assert_eq!(iter.next(), None);
929     /// ```
930     #[inline]
931     #[stable(feature = "rust1", since = "1.0.0")]
932     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
933         Skip { iter: self, n }
934     }
935
936     /// Creates an iterator that yields its first `n` elements.
937     ///
938     /// # Examples
939     ///
940     /// Basic usage:
941     ///
942     /// ```
943     /// let a = [1, 2, 3];
944     ///
945     /// let mut iter = a.iter().take(2);
946     ///
947     /// assert_eq!(iter.next(), Some(&1));
948     /// assert_eq!(iter.next(), Some(&2));
949     /// assert_eq!(iter.next(), None);
950     /// ```
951     ///
952     /// `take()` is often used with an infinite iterator, to make it finite:
953     ///
954     /// ```
955     /// let mut iter = (0..).take(3);
956     ///
957     /// assert_eq!(iter.next(), Some(0));
958     /// assert_eq!(iter.next(), Some(1));
959     /// assert_eq!(iter.next(), Some(2));
960     /// assert_eq!(iter.next(), None);
961     /// ```
962     #[inline]
963     #[stable(feature = "rust1", since = "1.0.0")]
964     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
965         Take { iter: self, n }
966     }
967
968     /// An iterator adaptor similar to [`fold`] that holds internal state and
969     /// produces a new iterator.
970     ///
971     /// [`fold`]: #method.fold
972     ///
973     /// `scan()` takes two arguments: an initial value which seeds the internal
974     /// state, and a closure with two arguments, the first being a mutable
975     /// reference to the internal state and the second an iterator element.
976     /// The closure can assign to the internal state to share state between
977     /// iterations.
978     ///
979     /// On iteration, the closure will be applied to each element of the
980     /// iterator and the return value from the closure, an [`Option`], is
981     /// yielded by the iterator.
982     ///
983     /// [`Option`]: ../../std/option/enum.Option.html
984     ///
985     /// # Examples
986     ///
987     /// Basic usage:
988     ///
989     /// ```
990     /// let a = [1, 2, 3];
991     ///
992     /// let mut iter = a.iter().scan(1, |state, &x| {
993     ///     // each iteration, we'll multiply the state by the element
994     ///     *state = *state * x;
995     ///
996     ///     // then, we'll yield the negation of the state
997     ///     Some(-*state)
998     /// });
999     ///
1000     /// assert_eq!(iter.next(), Some(-1));
1001     /// assert_eq!(iter.next(), Some(-2));
1002     /// assert_eq!(iter.next(), Some(-6));
1003     /// assert_eq!(iter.next(), None);
1004     /// ```
1005     #[inline]
1006     #[stable(feature = "rust1", since = "1.0.0")]
1007     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1008         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1009     {
1010         Scan { iter: self, f, state: initial_state }
1011     }
1012
1013     /// Creates an iterator that works like map, but flattens nested structure.
1014     ///
1015     /// The [`map`] adapter is very useful, but only when the closure
1016     /// argument produces values. If it produces an iterator instead, there's
1017     /// an extra layer of indirection. `flat_map()` will remove this extra layer
1018     /// on its own.
1019     ///
1020     /// You can think of `flat_map(f)` as the semantic equivalent
1021     /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1022     ///
1023     /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1024     /// one item for each element, and `flat_map()`'s closure returns an
1025     /// iterator for each element.
1026     ///
1027     /// [`map`]: #method.map
1028     /// [`flatten`]: #method.flatten
1029     ///
1030     /// # Examples
1031     ///
1032     /// Basic usage:
1033     ///
1034     /// ```
1035     /// let words = ["alpha", "beta", "gamma"];
1036     ///
1037     /// // chars() returns an iterator
1038     /// let merged: String = words.iter()
1039     ///                           .flat_map(|s| s.chars())
1040     ///                           .collect();
1041     /// assert_eq!(merged, "alphabetagamma");
1042     /// ```
1043     #[inline]
1044     #[stable(feature = "rust1", since = "1.0.0")]
1045     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1046         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1047     {
1048         FlatMap { inner: flatten_compat(self.map(f)) }
1049     }
1050
1051     /// Creates an iterator that flattens nested structure.
1052     ///
1053     /// This is useful when you have an iterator of iterators or an iterator of
1054     /// things that can be turned into iterators and you want to remove one
1055     /// level of indirection.
1056     ///
1057     /// # Examples
1058     ///
1059     /// Basic usage:
1060     ///
1061     /// ```
1062     /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1063     /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1064     /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1065     /// ```
1066     ///
1067     /// Mapping and then flattening:
1068     ///
1069     /// ```
1070     /// let words = ["alpha", "beta", "gamma"];
1071     ///
1072     /// // chars() returns an iterator
1073     /// let merged: String = words.iter()
1074     ///                           .map(|s| s.chars())
1075     ///                           .flatten()
1076     ///                           .collect();
1077     /// assert_eq!(merged, "alphabetagamma");
1078     /// ```
1079     ///
1080     /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1081     /// in this case since it conveys intent more clearly:
1082     ///
1083     /// ```
1084     /// let words = ["alpha", "beta", "gamma"];
1085     ///
1086     /// // chars() returns an iterator
1087     /// let merged: String = words.iter()
1088     ///                           .flat_map(|s| s.chars())
1089     ///                           .collect();
1090     /// assert_eq!(merged, "alphabetagamma");
1091     /// ```
1092     ///
1093     /// Flattening once only removes one level of nesting:
1094     ///
1095     /// ```
1096     /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1097     ///
1098     /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1099     /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1100     ///
1101     /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1102     /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1103     /// ```
1104     ///
1105     /// Here we see that `flatten()` does not perform a "deep" flatten.
1106     /// Instead, only one level of nesting is removed. That is, if you
1107     /// `flatten()` a three-dimensional array the result will be
1108     /// two-dimensional and not one-dimensional. To get a one-dimensional
1109     /// structure, you have to `flatten()` again.
1110     ///
1111     /// [`flat_map()`]: #method.flat_map
1112     #[inline]
1113     #[stable(feature = "iterator_flatten", since = "1.29")]
1114     fn flatten(self) -> Flatten<Self>
1115     where Self: Sized, Self::Item: IntoIterator {
1116         Flatten { inner: flatten_compat(self) }
1117     }
1118
1119     /// Creates an iterator which ends after the first [`None`].
1120     ///
1121     /// After an iterator returns [`None`], future calls may or may not yield
1122     /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1123     /// [`None`] is given, it will always return [`None`] forever.
1124     ///
1125     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1126     /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1127     ///
1128     /// # Examples
1129     ///
1130     /// Basic usage:
1131     ///
1132     /// ```
1133     /// // an iterator which alternates between Some and None
1134     /// struct Alternate {
1135     ///     state: i32,
1136     /// }
1137     ///
1138     /// impl Iterator for Alternate {
1139     ///     type Item = i32;
1140     ///
1141     ///     fn next(&mut self) -> Option<i32> {
1142     ///         let val = self.state;
1143     ///         self.state = self.state + 1;
1144     ///
1145     ///         // if it's even, Some(i32), else None
1146     ///         if val % 2 == 0 {
1147     ///             Some(val)
1148     ///         } else {
1149     ///             None
1150     ///         }
1151     ///     }
1152     /// }
1153     ///
1154     /// let mut iter = Alternate { state: 0 };
1155     ///
1156     /// // we can see our iterator going back and forth
1157     /// assert_eq!(iter.next(), Some(0));
1158     /// assert_eq!(iter.next(), None);
1159     /// assert_eq!(iter.next(), Some(2));
1160     /// assert_eq!(iter.next(), None);
1161     ///
1162     /// // however, once we fuse it...
1163     /// let mut iter = iter.fuse();
1164     ///
1165     /// assert_eq!(iter.next(), Some(4));
1166     /// assert_eq!(iter.next(), None);
1167     ///
1168     /// // it will always return None after the first time.
1169     /// assert_eq!(iter.next(), None);
1170     /// assert_eq!(iter.next(), None);
1171     /// assert_eq!(iter.next(), None);
1172     /// ```
1173     #[inline]
1174     #[stable(feature = "rust1", since = "1.0.0")]
1175     fn fuse(self) -> Fuse<Self> where Self: Sized {
1176         Fuse{iter: self, done: false}
1177     }
1178
1179     /// Do something with each element of an iterator, passing the value on.
1180     ///
1181     /// When using iterators, you'll often chain several of them together.
1182     /// While working on such code, you might want to check out what's
1183     /// happening at various parts in the pipeline. To do that, insert
1184     /// a call to `inspect()`.
1185     ///
1186     /// It's more common for `inspect()` to be used as a debugging tool than to
1187     /// exist in your final code, but applications may find it useful in certain
1188     /// situations when errors need to be logged before being discarded.
1189     ///
1190     /// # Examples
1191     ///
1192     /// Basic usage:
1193     ///
1194     /// ```
1195     /// let a = [1, 4, 2, 3];
1196     ///
1197     /// // this iterator sequence is complex.
1198     /// let sum = a.iter()
1199     ///     .cloned()
1200     ///     .filter(|x| x % 2 == 0)
1201     ///     .fold(0, |sum, i| sum + i);
1202     ///
1203     /// println!("{}", sum);
1204     ///
1205     /// // let's add some inspect() calls to investigate what's happening
1206     /// let sum = a.iter()
1207     ///     .cloned()
1208     ///     .inspect(|x| println!("about to filter: {}", x))
1209     ///     .filter(|x| x % 2 == 0)
1210     ///     .inspect(|x| println!("made it through filter: {}", x))
1211     ///     .fold(0, |sum, i| sum + i);
1212     ///
1213     /// println!("{}", sum);
1214     /// ```
1215     ///
1216     /// This will print:
1217     ///
1218     /// ```text
1219     /// 6
1220     /// about to filter: 1
1221     /// about to filter: 4
1222     /// made it through filter: 4
1223     /// about to filter: 2
1224     /// made it through filter: 2
1225     /// about to filter: 3
1226     /// 6
1227     /// ```
1228     ///
1229     /// Logging errors before discarding them:
1230     ///
1231     /// ```
1232     /// let lines = ["1", "2", "a"];
1233     ///
1234     /// let sum: i32 = lines
1235     ///     .iter()
1236     ///     .map(|line| line.parse::<i32>())
1237     ///     .inspect(|num| {
1238     ///         if let Err(ref e) = *num {
1239     ///             println!("Parsing error: {}", e);
1240     ///         }
1241     ///     })
1242     ///     .filter_map(Result::ok)
1243     ///     .sum();
1244     ///
1245     /// println!("Sum: {}", sum);
1246     /// ```
1247     ///
1248     /// This will print:
1249     ///
1250     /// ```text
1251     /// Parsing error: invalid digit found in string
1252     /// Sum: 3
1253     /// ```
1254     #[inline]
1255     #[stable(feature = "rust1", since = "1.0.0")]
1256     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1257         Self: Sized, F: FnMut(&Self::Item),
1258     {
1259         Inspect { iter: self, f }
1260     }
1261
1262     /// Borrows an iterator, rather than consuming it.
1263     ///
1264     /// This is useful to allow applying iterator adaptors while still
1265     /// retaining ownership of the original iterator.
1266     ///
1267     /// # Examples
1268     ///
1269     /// Basic usage:
1270     ///
1271     /// ```
1272     /// let a = [1, 2, 3];
1273     ///
1274     /// let iter = a.into_iter();
1275     ///
1276     /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1277     ///
1278     /// assert_eq!(sum, 6);
1279     ///
1280     /// // if we try to use iter again, it won't work. The following line
1281     /// // gives "error: use of moved value: `iter`
1282     /// // assert_eq!(iter.next(), None);
1283     ///
1284     /// // let's try that again
1285     /// let a = [1, 2, 3];
1286     ///
1287     /// let mut iter = a.into_iter();
1288     ///
1289     /// // instead, we add in a .by_ref()
1290     /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1291     ///
1292     /// assert_eq!(sum, 3);
1293     ///
1294     /// // now this is just fine:
1295     /// assert_eq!(iter.next(), Some(&3));
1296     /// assert_eq!(iter.next(), None);
1297     /// ```
1298     #[stable(feature = "rust1", since = "1.0.0")]
1299     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1300
1301     /// Transforms an iterator into a collection.
1302     ///
1303     /// `collect()` can take anything iterable, and turn it into a relevant
1304     /// collection. This is one of the more powerful methods in the standard
1305     /// library, used in a variety of contexts.
1306     ///
1307     /// The most basic pattern in which `collect()` is used is to turn one
1308     /// collection into another. You take a collection, call [`iter`] on it,
1309     /// do a bunch of transformations, and then `collect()` at the end.
1310     ///
1311     /// One of the keys to `collect()`'s power is that many things you might
1312     /// not think of as 'collections' actually are. For example, a [`String`]
1313     /// is a collection of [`char`]s. And a collection of
1314     /// [`Result<T, E>`][`Result`] can be thought of as single
1315     /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1316     ///
1317     /// Because `collect()` is so general, it can cause problems with type
1318     /// inference. As such, `collect()` is one of the few times you'll see
1319     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1320     /// helps the inference algorithm understand specifically which collection
1321     /// you're trying to collect into.
1322     ///
1323     /// # Examples
1324     ///
1325     /// Basic usage:
1326     ///
1327     /// ```
1328     /// let a = [1, 2, 3];
1329     ///
1330     /// let doubled: Vec<i32> = a.iter()
1331     ///                          .map(|&x| x * 2)
1332     ///                          .collect();
1333     ///
1334     /// assert_eq!(vec![2, 4, 6], doubled);
1335     /// ```
1336     ///
1337     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1338     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1339     ///
1340     /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1341     ///
1342     /// ```
1343     /// use std::collections::VecDeque;
1344     ///
1345     /// let a = [1, 2, 3];
1346     ///
1347     /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1348     ///
1349     /// assert_eq!(2, doubled[0]);
1350     /// assert_eq!(4, doubled[1]);
1351     /// assert_eq!(6, doubled[2]);
1352     /// ```
1353     ///
1354     /// Using the 'turbofish' instead of annotating `doubled`:
1355     ///
1356     /// ```
1357     /// let a = [1, 2, 3];
1358     ///
1359     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1360     ///
1361     /// assert_eq!(vec![2, 4, 6], doubled);
1362     /// ```
1363     ///
1364     /// Because `collect()` only cares about what you're collecting into, you can
1365     /// still use a partial type hint, `_`, with the turbofish:
1366     ///
1367     /// ```
1368     /// let a = [1, 2, 3];
1369     ///
1370     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1371     ///
1372     /// assert_eq!(vec![2, 4, 6], doubled);
1373     /// ```
1374     ///
1375     /// Using `collect()` to make a [`String`]:
1376     ///
1377     /// ```
1378     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1379     ///
1380     /// let hello: String = chars.iter()
1381     ///     .map(|&x| x as u8)
1382     ///     .map(|x| (x + 1) as char)
1383     ///     .collect();
1384     ///
1385     /// assert_eq!("hello", hello);
1386     /// ```
1387     ///
1388     /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1389     /// see if any of them failed:
1390     ///
1391     /// ```
1392     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1393     ///
1394     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1395     ///
1396     /// // gives us the first error
1397     /// assert_eq!(Err("nope"), result);
1398     ///
1399     /// let results = [Ok(1), Ok(3)];
1400     ///
1401     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1402     ///
1403     /// // gives us the list of answers
1404     /// assert_eq!(Ok(vec![1, 3]), result);
1405     /// ```
1406     ///
1407     /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1408     /// [`String`]: ../../std/string/struct.String.html
1409     /// [`char`]: ../../std/primitive.char.html
1410     /// [`Result`]: ../../std/result/enum.Result.html
1411     #[inline]
1412     #[stable(feature = "rust1", since = "1.0.0")]
1413     #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1414     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1415         FromIterator::from_iter(self)
1416     }
1417
1418     /// Consumes an iterator, creating two collections from it.
1419     ///
1420     /// The predicate passed to `partition()` can return `true`, or `false`.
1421     /// `partition()` returns a pair, all of the elements for which it returned
1422     /// `true`, and all of the elements for which it returned `false`.
1423     ///
1424     /// # Examples
1425     ///
1426     /// Basic usage:
1427     ///
1428     /// ```
1429     /// let a = [1, 2, 3];
1430     ///
1431     /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1432     ///     .into_iter()
1433     ///     .partition(|&n| n % 2 == 0);
1434     ///
1435     /// assert_eq!(even, vec![2]);
1436     /// assert_eq!(odd, vec![1, 3]);
1437     /// ```
1438     #[stable(feature = "rust1", since = "1.0.0")]
1439     fn partition<B, F>(self, mut f: F) -> (B, B) where
1440         Self: Sized,
1441         B: Default + Extend<Self::Item>,
1442         F: FnMut(&Self::Item) -> bool
1443     {
1444         let mut left: B = Default::default();
1445         let mut right: B = Default::default();
1446
1447         for x in self {
1448             if f(&x) {
1449                 left.extend(Some(x))
1450             } else {
1451                 right.extend(Some(x))
1452             }
1453         }
1454
1455         (left, right)
1456     }
1457
1458     /// An iterator method that applies a function as long as it returns
1459     /// successfully, producing a single, final value.
1460     ///
1461     /// `try_fold()` takes two arguments: an initial value, and a closure with
1462     /// two arguments: an 'accumulator', and an element. The closure either
1463     /// returns successfully, with the value that the accumulator should have
1464     /// for the next iteration, or it returns failure, with an error value that
1465     /// is propagated back to the caller immediately (short-circuiting).
1466     ///
1467     /// The initial value is the value the accumulator will have on the first
1468     /// call.  If applying the closure succeeded against every element of the
1469     /// iterator, `try_fold()` returns the final accumulator as success.
1470     ///
1471     /// Folding is useful whenever you have a collection of something, and want
1472     /// to produce a single value from it.
1473     ///
1474     /// # Note to Implementors
1475     ///
1476     /// Most of the other (forward) methods have default implementations in
1477     /// terms of this one, so try to implement this explicitly if it can
1478     /// do something better than the default `for` loop implementation.
1479     ///
1480     /// In particular, try to have this call `try_fold()` on the internal parts
1481     /// from which this iterator is composed.  If multiple calls are needed,
1482     /// the `?` operator may be convenient for chaining the accumulator value
1483     /// along, but beware any invariants that need to be upheld before those
1484     /// early returns.  This is a `&mut self` method, so iteration needs to be
1485     /// resumable after hitting an error here.
1486     ///
1487     /// # Examples
1488     ///
1489     /// Basic usage:
1490     ///
1491     /// ```
1492     /// let a = [1, 2, 3];
1493     ///
1494     /// // the checked sum of all of the elements of the array
1495     /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1496     ///
1497     /// assert_eq!(sum, Some(6));
1498     /// ```
1499     ///
1500     /// Short-circuiting:
1501     ///
1502     /// ```
1503     /// let a = [10, 20, 30, 100, 40, 50];
1504     /// let mut it = a.iter();
1505     ///
1506     /// // This sum overflows when adding the 100 element
1507     /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1508     /// assert_eq!(sum, None);
1509     ///
1510     /// // Because it short-circuited, the remaining elements are still
1511     /// // available through the iterator.
1512     /// assert_eq!(it.len(), 2);
1513     /// assert_eq!(it.next(), Some(&40));
1514     /// ```
1515     #[inline]
1516     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1517     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1518         Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1519     {
1520         let mut accum = init;
1521         while let Some(x) = self.next() {
1522             accum = f(accum, x)?;
1523         }
1524         Try::from_ok(accum)
1525     }
1526
1527     /// An iterator method that applies a fallible function to each item in the
1528     /// iterator, stopping at the first error and returning that error.
1529     ///
1530     /// This can also be thought of as the fallible form of [`for_each()`]
1531     /// or as the stateless version of [`try_fold()`].
1532     ///
1533     /// [`for_each()`]: #method.for_each
1534     /// [`try_fold()`]: #method.try_fold
1535     ///
1536     /// # Examples
1537     ///
1538     /// ```
1539     /// use std::fs::rename;
1540     /// use std::io::{stdout, Write};
1541     /// use std::path::Path;
1542     ///
1543     /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1544     ///
1545     /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1546     /// assert!(res.is_ok());
1547     ///
1548     /// let mut it = data.iter().cloned();
1549     /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1550     /// assert!(res.is_err());
1551     /// // It short-circuited, so the remaining items are still in the iterator:
1552     /// assert_eq!(it.next(), Some("stale_bread.json"));
1553     /// ```
1554     #[inline]
1555     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1556     fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1557         Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1558     {
1559         self.try_fold((), move |(), x| f(x))
1560     }
1561
1562     /// An iterator method that applies a function, producing a single, final value.
1563     ///
1564     /// `fold()` takes two arguments: an initial value, and a closure with two
1565     /// arguments: an 'accumulator', and an element. The closure returns the value that
1566     /// the accumulator should have for the next iteration.
1567     ///
1568     /// The initial value is the value the accumulator will have on the first
1569     /// call.
1570     ///
1571     /// After applying this closure to every element of the iterator, `fold()`
1572     /// returns the accumulator.
1573     ///
1574     /// This operation is sometimes called 'reduce' or 'inject'.
1575     ///
1576     /// Folding is useful whenever you have a collection of something, and want
1577     /// to produce a single value from it.
1578     ///
1579     /// Note: `fold()`, and similar methods that traverse the entire iterator,
1580     /// may not terminate for infinite iterators, even on traits for which a
1581     /// result is determinable in finite time.
1582     ///
1583     /// # Examples
1584     ///
1585     /// Basic usage:
1586     ///
1587     /// ```
1588     /// let a = [1, 2, 3];
1589     ///
1590     /// // the sum of all of the elements of the array
1591     /// let sum = a.iter().fold(0, |acc, x| acc + x);
1592     ///
1593     /// assert_eq!(sum, 6);
1594     /// ```
1595     ///
1596     /// Let's walk through each step of the iteration here:
1597     ///
1598     /// | element | acc | x | result |
1599     /// |---------|-----|---|--------|
1600     /// |         | 0   |   |        |
1601     /// | 1       | 0   | 1 | 1      |
1602     /// | 2       | 1   | 2 | 3      |
1603     /// | 3       | 3   | 3 | 6      |
1604     ///
1605     /// And so, our final result, `6`.
1606     ///
1607     /// It's common for people who haven't used iterators a lot to
1608     /// use a `for` loop with a list of things to build up a result. Those
1609     /// can be turned into `fold()`s:
1610     ///
1611     /// [`for`]: ../../book/first-edition/loops.html#for
1612     ///
1613     /// ```
1614     /// let numbers = [1, 2, 3, 4, 5];
1615     ///
1616     /// let mut result = 0;
1617     ///
1618     /// // for loop:
1619     /// for i in &numbers {
1620     ///     result = result + i;
1621     /// }
1622     ///
1623     /// // fold:
1624     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1625     ///
1626     /// // they're the same
1627     /// assert_eq!(result, result2);
1628     /// ```
1629     #[inline]
1630     #[stable(feature = "rust1", since = "1.0.0")]
1631     fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1632         Self: Sized, F: FnMut(B, Self::Item) -> B,
1633     {
1634         self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1635     }
1636
1637     /// Tests if every element of the iterator matches a predicate.
1638     ///
1639     /// `all()` takes a closure that returns `true` or `false`. It applies
1640     /// this closure to each element of the iterator, and if they all return
1641     /// `true`, then so does `all()`. If any of them return `false`, it
1642     /// returns `false`.
1643     ///
1644     /// `all()` is short-circuiting; in other words, it will stop processing
1645     /// as soon as it finds a `false`, given that no matter what else happens,
1646     /// the result will also be `false`.
1647     ///
1648     /// An empty iterator returns `true`.
1649     ///
1650     /// # Examples
1651     ///
1652     /// Basic usage:
1653     ///
1654     /// ```
1655     /// let a = [1, 2, 3];
1656     ///
1657     /// assert!(a.iter().all(|&x| x > 0));
1658     ///
1659     /// assert!(!a.iter().all(|&x| x > 2));
1660     /// ```
1661     ///
1662     /// Stopping at the first `false`:
1663     ///
1664     /// ```
1665     /// let a = [1, 2, 3];
1666     ///
1667     /// let mut iter = a.iter();
1668     ///
1669     /// assert!(!iter.all(|&x| x != 2));
1670     ///
1671     /// // we can still use `iter`, as there are more elements.
1672     /// assert_eq!(iter.next(), Some(&3));
1673     /// ```
1674     #[inline]
1675     #[stable(feature = "rust1", since = "1.0.0")]
1676     fn all<F>(&mut self, mut f: F) -> bool where
1677         Self: Sized, F: FnMut(Self::Item) -> bool
1678     {
1679         self.try_for_each(move |x| {
1680             if f(x) { LoopState::Continue(()) }
1681             else { LoopState::Break(()) }
1682         }) == LoopState::Continue(())
1683     }
1684
1685     /// Tests if any element of the iterator matches a predicate.
1686     ///
1687     /// `any()` takes a closure that returns `true` or `false`. It applies
1688     /// this closure to each element of the iterator, and if any of them return
1689     /// `true`, then so does `any()`. If they all return `false`, it
1690     /// returns `false`.
1691     ///
1692     /// `any()` is short-circuiting; in other words, it will stop processing
1693     /// as soon as it finds a `true`, given that no matter what else happens,
1694     /// the result will also be `true`.
1695     ///
1696     /// An empty iterator returns `false`.
1697     ///
1698     /// # Examples
1699     ///
1700     /// Basic usage:
1701     ///
1702     /// ```
1703     /// let a = [1, 2, 3];
1704     ///
1705     /// assert!(a.iter().any(|&x| x > 0));
1706     ///
1707     /// assert!(!a.iter().any(|&x| x > 5));
1708     /// ```
1709     ///
1710     /// Stopping at the first `true`:
1711     ///
1712     /// ```
1713     /// let a = [1, 2, 3];
1714     ///
1715     /// let mut iter = a.iter();
1716     ///
1717     /// assert!(iter.any(|&x| x != 2));
1718     ///
1719     /// // we can still use `iter`, as there are more elements.
1720     /// assert_eq!(iter.next(), Some(&2));
1721     /// ```
1722     #[inline]
1723     #[stable(feature = "rust1", since = "1.0.0")]
1724     fn any<F>(&mut self, mut f: F) -> bool where
1725         Self: Sized,
1726         F: FnMut(Self::Item) -> bool
1727     {
1728         self.try_for_each(move |x| {
1729             if f(x) { LoopState::Break(()) }
1730             else { LoopState::Continue(()) }
1731         }) == LoopState::Break(())
1732     }
1733
1734     /// Searches for an element of an iterator that satisfies a predicate.
1735     ///
1736     /// `find()` takes a closure that returns `true` or `false`. It applies
1737     /// this closure to each element of the iterator, and if any of them return
1738     /// `true`, then `find()` returns [`Some(element)`]. If they all return
1739     /// `false`, it returns [`None`].
1740     ///
1741     /// `find()` is short-circuiting; in other words, it will stop processing
1742     /// as soon as the closure returns `true`.
1743     ///
1744     /// Because `find()` takes a reference, and many iterators iterate over
1745     /// references, this leads to a possibly confusing situation where the
1746     /// argument is a double reference. You can see this effect in the
1747     /// examples below, with `&&x`.
1748     ///
1749     /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1750     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1751     ///
1752     /// # Examples
1753     ///
1754     /// Basic usage:
1755     ///
1756     /// ```
1757     /// let a = [1, 2, 3];
1758     ///
1759     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1760     ///
1761     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1762     /// ```
1763     ///
1764     /// Stopping at the first `true`:
1765     ///
1766     /// ```
1767     /// let a = [1, 2, 3];
1768     ///
1769     /// let mut iter = a.iter();
1770     ///
1771     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1772     ///
1773     /// // we can still use `iter`, as there are more elements.
1774     /// assert_eq!(iter.next(), Some(&3));
1775     /// ```
1776     #[inline]
1777     #[stable(feature = "rust1", since = "1.0.0")]
1778     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1779         Self: Sized,
1780         P: FnMut(&Self::Item) -> bool,
1781     {
1782         self.try_for_each(move |x| {
1783             if predicate(&x) { LoopState::Break(x) }
1784             else { LoopState::Continue(()) }
1785         }).break_value()
1786     }
1787
1788     /// Applies function to the elements of iterator and returns
1789     /// the first non-none result.
1790     ///
1791     /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1792     ///
1793     ///
1794     /// # Examples
1795     ///
1796     /// ```
1797     /// #![feature(iterator_find_map)]
1798     /// let a = ["lol", "NaN", "2", "5"];
1799     ///
1800     /// let mut first_number = a.iter().find_map(|s| s.parse().ok());
1801     ///
1802     /// assert_eq!(first_number, Some(2));
1803     /// ```
1804     #[inline]
1805     #[unstable(feature = "iterator_find_map",
1806                reason = "unstable new API",
1807                issue = "49602")]
1808     fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1809         Self: Sized,
1810         F: FnMut(Self::Item) -> Option<B>,
1811     {
1812         self.try_for_each(move |x| {
1813             match f(x) {
1814                 Some(x) => LoopState::Break(x),
1815                 None => LoopState::Continue(()),
1816             }
1817         }).break_value()
1818     }
1819
1820     /// Searches for an element in an iterator, returning its index.
1821     ///
1822     /// `position()` takes a closure that returns `true` or `false`. It applies
1823     /// this closure to each element of the iterator, and if one of them
1824     /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1825     /// them return `false`, it returns [`None`].
1826     ///
1827     /// `position()` is short-circuiting; in other words, it will stop
1828     /// processing as soon as it finds a `true`.
1829     ///
1830     /// # Overflow Behavior
1831     ///
1832     /// The method does no guarding against overflows, so if there are more
1833     /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1834     /// result or panics. If debug assertions are enabled, a panic is
1835     /// guaranteed.
1836     ///
1837     /// # Panics
1838     ///
1839     /// This function might panic if the iterator has more than `usize::MAX`
1840     /// non-matching elements.
1841     ///
1842     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1843     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1844     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1845     ///
1846     /// # Examples
1847     ///
1848     /// Basic usage:
1849     ///
1850     /// ```
1851     /// let a = [1, 2, 3];
1852     ///
1853     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1854     ///
1855     /// assert_eq!(a.iter().position(|&x| x == 5), None);
1856     /// ```
1857     ///
1858     /// Stopping at the first `true`:
1859     ///
1860     /// ```
1861     /// let a = [1, 2, 3, 4];
1862     ///
1863     /// let mut iter = a.iter();
1864     ///
1865     /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1866     ///
1867     /// // we can still use `iter`, as there are more elements.
1868     /// assert_eq!(iter.next(), Some(&3));
1869     ///
1870     /// // The returned index depends on iterator state
1871     /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1872     ///
1873     /// ```
1874     #[inline]
1875     #[rustc_inherit_overflow_checks]
1876     #[stable(feature = "rust1", since = "1.0.0")]
1877     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1878         Self: Sized,
1879         P: FnMut(Self::Item) -> bool,
1880     {
1881         // The addition might panic on overflow
1882         self.try_fold(0, move |i, x| {
1883             if predicate(x) { LoopState::Break(i) }
1884             else { LoopState::Continue(i + 1) }
1885         }).break_value()
1886     }
1887
1888     /// Searches for an element in an iterator from the right, returning its
1889     /// index.
1890     ///
1891     /// `rposition()` takes a closure that returns `true` or `false`. It applies
1892     /// this closure to each element of the iterator, starting from the end,
1893     /// and if one of them returns `true`, then `rposition()` returns
1894     /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1895     ///
1896     /// `rposition()` is short-circuiting; in other words, it will stop
1897     /// processing as soon as it finds a `true`.
1898     ///
1899     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1900     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1901     ///
1902     /// # Examples
1903     ///
1904     /// Basic usage:
1905     ///
1906     /// ```
1907     /// let a = [1, 2, 3];
1908     ///
1909     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1910     ///
1911     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1912     /// ```
1913     ///
1914     /// Stopping at the first `true`:
1915     ///
1916     /// ```
1917     /// let a = [1, 2, 3];
1918     ///
1919     /// let mut iter = a.iter();
1920     ///
1921     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1922     ///
1923     /// // we can still use `iter`, as there are more elements.
1924     /// assert_eq!(iter.next(), Some(&1));
1925     /// ```
1926     #[inline]
1927     #[stable(feature = "rust1", since = "1.0.0")]
1928     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1929         P: FnMut(Self::Item) -> bool,
1930         Self: Sized + ExactSizeIterator + DoubleEndedIterator
1931     {
1932         // No need for an overflow check here, because `ExactSizeIterator`
1933         // implies that the number of elements fits into a `usize`.
1934         let n = self.len();
1935         self.try_rfold(n, move |i, x| {
1936             let i = i - 1;
1937             if predicate(x) { LoopState::Break(i) }
1938             else { LoopState::Continue(i) }
1939         }).break_value()
1940     }
1941
1942     /// Returns the maximum element of an iterator.
1943     ///
1944     /// If several elements are equally maximum, the last element is
1945     /// returned. If the iterator is empty, [`None`] is returned.
1946     ///
1947     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1948     ///
1949     /// # Examples
1950     ///
1951     /// Basic usage:
1952     ///
1953     /// ```
1954     /// let a = [1, 2, 3];
1955     /// let b: Vec<u32> = Vec::new();
1956     ///
1957     /// assert_eq!(a.iter().max(), Some(&3));
1958     /// assert_eq!(b.iter().max(), None);
1959     /// ```
1960     #[inline]
1961     #[stable(feature = "rust1", since = "1.0.0")]
1962     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1963     {
1964         select_fold1(self,
1965                      |_| (),
1966                      // switch to y even if it is only equal, to preserve
1967                      // stability.
1968                      |_, x, _, y| *x <= *y)
1969             .map(|(_, x)| x)
1970     }
1971
1972     /// Returns the minimum element of an iterator.
1973     ///
1974     /// If several elements are equally minimum, the first element is
1975     /// returned. If the iterator is empty, [`None`] is returned.
1976     ///
1977     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1978     ///
1979     /// # Examples
1980     ///
1981     /// Basic usage:
1982     ///
1983     /// ```
1984     /// let a = [1, 2, 3];
1985     /// let b: Vec<u32> = Vec::new();
1986     ///
1987     /// assert_eq!(a.iter().min(), Some(&1));
1988     /// assert_eq!(b.iter().min(), None);
1989     /// ```
1990     #[inline]
1991     #[stable(feature = "rust1", since = "1.0.0")]
1992     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1993     {
1994         select_fold1(self,
1995                      |_| (),
1996                      // only switch to y if it is strictly smaller, to
1997                      // preserve stability.
1998                      |_, x, _, y| *x > *y)
1999             .map(|(_, x)| x)
2000     }
2001
2002     /// Returns the element that gives the maximum value from the
2003     /// specified function.
2004     ///
2005     /// If several elements are equally maximum, the last element is
2006     /// returned. If the iterator is empty, [`None`] is returned.
2007     ///
2008     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2009     ///
2010     /// # Examples
2011     ///
2012     /// ```
2013     /// let a = [-3_i32, 0, 1, 5, -10];
2014     /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2015     /// ```
2016     #[inline]
2017     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2018     fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2019         where Self: Sized, F: FnMut(&Self::Item) -> B,
2020     {
2021         select_fold1(self,
2022                      f,
2023                      // switch to y even if it is only equal, to preserve
2024                      // stability.
2025                      |x_p, _, y_p, _| x_p <= y_p)
2026             .map(|(_, x)| x)
2027     }
2028
2029     /// Returns the element that gives the maximum value with respect to the
2030     /// specified comparison function.
2031     ///
2032     /// If several elements are equally maximum, the last element is
2033     /// returned. If the iterator is empty, [`None`] is returned.
2034     ///
2035     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2036     ///
2037     /// # Examples
2038     ///
2039     /// ```
2040     /// let a = [-3_i32, 0, 1, 5, -10];
2041     /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2042     /// ```
2043     #[inline]
2044     #[stable(feature = "iter_max_by", since = "1.15.0")]
2045     fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2046         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2047     {
2048         select_fold1(self,
2049                      |_| (),
2050                      // switch to y even if it is only equal, to preserve
2051                      // stability.
2052                      |_, x, _, y| Ordering::Greater != compare(x, y))
2053             .map(|(_, x)| x)
2054     }
2055
2056     /// Returns the element that gives the minimum value from the
2057     /// specified function.
2058     ///
2059     /// If several elements are equally minimum, the first element is
2060     /// returned. If the iterator is empty, [`None`] is returned.
2061     ///
2062     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2063     ///
2064     /// # Examples
2065     ///
2066     /// ```
2067     /// let a = [-3_i32, 0, 1, 5, -10];
2068     /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2069     /// ```
2070     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2071     fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2072         where Self: Sized, F: FnMut(&Self::Item) -> B,
2073     {
2074         select_fold1(self,
2075                      f,
2076                      // only switch to y if it is strictly smaller, to
2077                      // preserve stability.
2078                      |x_p, _, y_p, _| x_p > y_p)
2079             .map(|(_, x)| x)
2080     }
2081
2082     /// Returns the element that gives the minimum value with respect to the
2083     /// specified comparison function.
2084     ///
2085     /// If several elements are equally minimum, the first element is
2086     /// returned. If the iterator is empty, [`None`] is returned.
2087     ///
2088     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2089     ///
2090     /// # Examples
2091     ///
2092     /// ```
2093     /// let a = [-3_i32, 0, 1, 5, -10];
2094     /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2095     /// ```
2096     #[inline]
2097     #[stable(feature = "iter_min_by", since = "1.15.0")]
2098     fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2099         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2100     {
2101         select_fold1(self,
2102                      |_| (),
2103                      // switch to y even if it is strictly smaller, to
2104                      // preserve stability.
2105                      |_, x, _, y| Ordering::Greater == compare(x, y))
2106             .map(|(_, x)| x)
2107     }
2108
2109
2110     /// Reverses an iterator's direction.
2111     ///
2112     /// Usually, iterators iterate from left to right. After using `rev()`,
2113     /// an iterator will instead iterate from right to left.
2114     ///
2115     /// This is only possible if the iterator has an end, so `rev()` only
2116     /// works on [`DoubleEndedIterator`]s.
2117     ///
2118     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2119     ///
2120     /// # Examples
2121     ///
2122     /// ```
2123     /// let a = [1, 2, 3];
2124     ///
2125     /// let mut iter = a.iter().rev();
2126     ///
2127     /// assert_eq!(iter.next(), Some(&3));
2128     /// assert_eq!(iter.next(), Some(&2));
2129     /// assert_eq!(iter.next(), Some(&1));
2130     ///
2131     /// assert_eq!(iter.next(), None);
2132     /// ```
2133     #[inline]
2134     #[stable(feature = "rust1", since = "1.0.0")]
2135     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2136         Rev{iter: self}
2137     }
2138
2139     /// Converts an iterator of pairs into a pair of containers.
2140     ///
2141     /// `unzip()` consumes an entire iterator of pairs, producing two
2142     /// collections: one from the left elements of the pairs, and one
2143     /// from the right elements.
2144     ///
2145     /// This function is, in some sense, the opposite of [`zip`].
2146     ///
2147     /// [`zip`]: #method.zip
2148     ///
2149     /// # Examples
2150     ///
2151     /// Basic usage:
2152     ///
2153     /// ```
2154     /// let a = [(1, 2), (3, 4)];
2155     ///
2156     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2157     ///
2158     /// assert_eq!(left, [1, 3]);
2159     /// assert_eq!(right, [2, 4]);
2160     /// ```
2161     #[stable(feature = "rust1", since = "1.0.0")]
2162     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2163         FromA: Default + Extend<A>,
2164         FromB: Default + Extend<B>,
2165         Self: Sized + Iterator<Item=(A, B)>,
2166     {
2167         let mut ts: FromA = Default::default();
2168         let mut us: FromB = Default::default();
2169
2170         self.for_each(|(t, u)| {
2171             ts.extend(Some(t));
2172             us.extend(Some(u));
2173         });
2174
2175         (ts, us)
2176     }
2177
2178     /// Creates an iterator which [`clone`]s all of its elements.
2179     ///
2180     /// This is useful when you have an iterator over `&T`, but you need an
2181     /// iterator over `T`.
2182     ///
2183     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2184     ///
2185     /// # Examples
2186     ///
2187     /// Basic usage:
2188     ///
2189     /// ```
2190     /// let a = [1, 2, 3];
2191     ///
2192     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2193     ///
2194     /// // cloned is the same as .map(|&x| x), for integers
2195     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2196     ///
2197     /// assert_eq!(v_cloned, vec![1, 2, 3]);
2198     /// assert_eq!(v_map, vec![1, 2, 3]);
2199     /// ```
2200     #[stable(feature = "rust1", since = "1.0.0")]
2201     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2202         where Self: Sized + Iterator<Item=&'a T>, T: Clone
2203     {
2204         Cloned { it: self }
2205     }
2206
2207     /// Repeats an iterator endlessly.
2208     ///
2209     /// Instead of stopping at [`None`], the iterator will instead start again,
2210     /// from the beginning. After iterating again, it will start at the
2211     /// beginning again. And again. And again. Forever.
2212     ///
2213     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2214     ///
2215     /// # Examples
2216     ///
2217     /// Basic usage:
2218     ///
2219     /// ```
2220     /// let a = [1, 2, 3];
2221     ///
2222     /// let mut it = a.iter().cycle();
2223     ///
2224     /// assert_eq!(it.next(), Some(&1));
2225     /// assert_eq!(it.next(), Some(&2));
2226     /// assert_eq!(it.next(), Some(&3));
2227     /// assert_eq!(it.next(), Some(&1));
2228     /// assert_eq!(it.next(), Some(&2));
2229     /// assert_eq!(it.next(), Some(&3));
2230     /// assert_eq!(it.next(), Some(&1));
2231     /// ```
2232     #[stable(feature = "rust1", since = "1.0.0")]
2233     #[inline]
2234     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2235         Cycle{orig: self.clone(), iter: self}
2236     }
2237
2238     /// Sums the elements of an iterator.
2239     ///
2240     /// Takes each element, adds them together, and returns the result.
2241     ///
2242     /// An empty iterator returns the zero value of the type.
2243     ///
2244     /// # Panics
2245     ///
2246     /// When calling `sum()` and a primitive integer type is being returned, this
2247     /// method will panic if the computation overflows and debug assertions are
2248     /// enabled.
2249     ///
2250     /// # Examples
2251     ///
2252     /// Basic usage:
2253     ///
2254     /// ```
2255     /// let a = [1, 2, 3];
2256     /// let sum: i32 = a.iter().sum();
2257     ///
2258     /// assert_eq!(sum, 6);
2259     /// ```
2260     #[stable(feature = "iter_arith", since = "1.11.0")]
2261     fn sum<S>(self) -> S
2262         where Self: Sized,
2263               S: Sum<Self::Item>,
2264     {
2265         Sum::sum(self)
2266     }
2267
2268     /// Iterates over the entire iterator, multiplying all the elements
2269     ///
2270     /// An empty iterator returns the one value of the type.
2271     ///
2272     /// # Panics
2273     ///
2274     /// When calling `product()` and a primitive integer type is being returned,
2275     /// method will panic if the computation overflows and debug assertions are
2276     /// enabled.
2277     ///
2278     /// # Examples
2279     ///
2280     /// ```
2281     /// fn factorial(n: u32) -> u32 {
2282     ///     (1..).take_while(|&i| i <= n).product()
2283     /// }
2284     /// assert_eq!(factorial(0), 1);
2285     /// assert_eq!(factorial(1), 1);
2286     /// assert_eq!(factorial(5), 120);
2287     /// ```
2288     #[stable(feature = "iter_arith", since = "1.11.0")]
2289     fn product<P>(self) -> P
2290         where Self: Sized,
2291               P: Product<Self::Item>,
2292     {
2293         Product::product(self)
2294     }
2295
2296     /// Lexicographically compares the elements of this `Iterator` with those
2297     /// of another.
2298     #[stable(feature = "iter_order", since = "1.5.0")]
2299     fn cmp<I>(mut self, other: I) -> Ordering where
2300         I: IntoIterator<Item = Self::Item>,
2301         Self::Item: Ord,
2302         Self: Sized,
2303     {
2304         let mut other = other.into_iter();
2305
2306         loop {
2307             let x = match self.next() {
2308                 None => if other.next().is_none() {
2309                     return Ordering::Equal
2310                 } else {
2311                     return Ordering::Less
2312                 },
2313                 Some(val) => val,
2314             };
2315
2316             let y = match other.next() {
2317                 None => return Ordering::Greater,
2318                 Some(val) => val,
2319             };
2320
2321             match x.cmp(&y) {
2322                 Ordering::Equal => (),
2323                 non_eq => return non_eq,
2324             }
2325         }
2326     }
2327
2328     /// Lexicographically compares the elements of this `Iterator` with those
2329     /// of another.
2330     #[stable(feature = "iter_order", since = "1.5.0")]
2331     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2332         I: IntoIterator,
2333         Self::Item: PartialOrd<I::Item>,
2334         Self: Sized,
2335     {
2336         let mut other = other.into_iter();
2337
2338         loop {
2339             let x = match self.next() {
2340                 None => if other.next().is_none() {
2341                     return Some(Ordering::Equal)
2342                 } else {
2343                     return Some(Ordering::Less)
2344                 },
2345                 Some(val) => val,
2346             };
2347
2348             let y = match other.next() {
2349                 None => return Some(Ordering::Greater),
2350                 Some(val) => val,
2351             };
2352
2353             match x.partial_cmp(&y) {
2354                 Some(Ordering::Equal) => (),
2355                 non_eq => return non_eq,
2356             }
2357         }
2358     }
2359
2360     /// Determines if the elements of this `Iterator` are equal to those of
2361     /// another.
2362     #[stable(feature = "iter_order", since = "1.5.0")]
2363     fn eq<I>(mut self, other: I) -> bool where
2364         I: IntoIterator,
2365         Self::Item: PartialEq<I::Item>,
2366         Self: Sized,
2367     {
2368         let mut other = other.into_iter();
2369
2370         loop {
2371             let x = match self.next() {
2372                 None => return other.next().is_none(),
2373                 Some(val) => val,
2374             };
2375
2376             let y = match other.next() {
2377                 None => return false,
2378                 Some(val) => val,
2379             };
2380
2381             if x != y { return false }
2382         }
2383     }
2384
2385     /// Determines if the elements of this `Iterator` are unequal to those of
2386     /// another.
2387     #[stable(feature = "iter_order", since = "1.5.0")]
2388     fn ne<I>(mut self, other: I) -> bool where
2389         I: IntoIterator,
2390         Self::Item: PartialEq<I::Item>,
2391         Self: Sized,
2392     {
2393         let mut other = other.into_iter();
2394
2395         loop {
2396             let x = match self.next() {
2397                 None => return other.next().is_some(),
2398                 Some(val) => val,
2399             };
2400
2401             let y = match other.next() {
2402                 None => return true,
2403                 Some(val) => val,
2404             };
2405
2406             if x != y { return true }
2407         }
2408     }
2409
2410     /// Determines if the elements of this `Iterator` are lexicographically
2411     /// less than those of another.
2412     #[stable(feature = "iter_order", since = "1.5.0")]
2413     fn lt<I>(mut self, other: I) -> bool where
2414         I: IntoIterator,
2415         Self::Item: PartialOrd<I::Item>,
2416         Self: Sized,
2417     {
2418         let mut other = other.into_iter();
2419
2420         loop {
2421             let x = match self.next() {
2422                 None => return other.next().is_some(),
2423                 Some(val) => val,
2424             };
2425
2426             let y = match other.next() {
2427                 None => return false,
2428                 Some(val) => val,
2429             };
2430
2431             match x.partial_cmp(&y) {
2432                 Some(Ordering::Less) => return true,
2433                 Some(Ordering::Equal) => (),
2434                 Some(Ordering::Greater) => return false,
2435                 None => return false,
2436             }
2437         }
2438     }
2439
2440     /// Determines if the elements of this `Iterator` are lexicographically
2441     /// less or equal to those of another.
2442     #[stable(feature = "iter_order", since = "1.5.0")]
2443     fn le<I>(mut self, other: I) -> bool where
2444         I: IntoIterator,
2445         Self::Item: PartialOrd<I::Item>,
2446         Self: Sized,
2447     {
2448         let mut other = other.into_iter();
2449
2450         loop {
2451             let x = match self.next() {
2452                 None => { other.next(); return true; },
2453                 Some(val) => val,
2454             };
2455
2456             let y = match other.next() {
2457                 None => return false,
2458                 Some(val) => val,
2459             };
2460
2461             match x.partial_cmp(&y) {
2462                 Some(Ordering::Less) => return true,
2463                 Some(Ordering::Equal) => (),
2464                 Some(Ordering::Greater) => return false,
2465                 None => return false,
2466             }
2467         }
2468     }
2469
2470     /// Determines if the elements of this `Iterator` are lexicographically
2471     /// greater than those of another.
2472     #[stable(feature = "iter_order", since = "1.5.0")]
2473     fn gt<I>(mut self, other: I) -> bool where
2474         I: IntoIterator,
2475         Self::Item: PartialOrd<I::Item>,
2476         Self: Sized,
2477     {
2478         let mut other = other.into_iter();
2479
2480         loop {
2481             let x = match self.next() {
2482                 None => { other.next(); return false; },
2483                 Some(val) => val,
2484             };
2485
2486             let y = match other.next() {
2487                 None => return true,
2488                 Some(val) => val,
2489             };
2490
2491             match x.partial_cmp(&y) {
2492                 Some(Ordering::Less) => return false,
2493                 Some(Ordering::Equal) => (),
2494                 Some(Ordering::Greater) => return true,
2495                 None => return false,
2496             }
2497         }
2498     }
2499
2500     /// Determines if the elements of this `Iterator` are lexicographically
2501     /// greater than or equal to those of another.
2502     #[stable(feature = "iter_order", since = "1.5.0")]
2503     fn ge<I>(mut self, other: I) -> bool where
2504         I: IntoIterator,
2505         Self::Item: PartialOrd<I::Item>,
2506         Self: Sized,
2507     {
2508         let mut other = other.into_iter();
2509
2510         loop {
2511             let x = match self.next() {
2512                 None => return other.next().is_none(),
2513                 Some(val) => val,
2514             };
2515
2516             let y = match other.next() {
2517                 None => return true,
2518                 Some(val) => val,
2519             };
2520
2521             match x.partial_cmp(&y) {
2522                 Some(Ordering::Less) => return false,
2523                 Some(Ordering::Equal) => (),
2524                 Some(Ordering::Greater) => return true,
2525                 None => return false,
2526             }
2527         }
2528     }
2529 }
2530
2531 /// Select an element from an iterator based on the given "projection"
2532 /// and "comparison" function.
2533 ///
2534 /// This is an idiosyncratic helper to try to factor out the
2535 /// commonalities of {max,min}{,_by}. In particular, this avoids
2536 /// having to implement optimizations several times.
2537 #[inline]
2538 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2539                                    mut f_proj: FProj,
2540                                    mut f_cmp: FCmp) -> Option<(B, I::Item)>
2541     where I: Iterator,
2542           FProj: FnMut(&I::Item) -> B,
2543           FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2544 {
2545     // start with the first element as our selection. This avoids
2546     // having to use `Option`s inside the loop, translating to a
2547     // sizeable performance gain (6x in one case).
2548     it.next().map(|first| {
2549         let first_p = f_proj(&first);
2550
2551         it.fold((first_p, first), |(sel_p, sel), x| {
2552             let x_p = f_proj(&x);
2553             if f_cmp(&sel_p, &sel, &x_p, &x) {
2554                 (x_p, x)
2555             } else {
2556                 (sel_p, sel)
2557             }
2558         })
2559     })
2560 }
2561
2562 #[stable(feature = "rust1", since = "1.0.0")]
2563 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2564     type Item = I::Item;
2565     fn next(&mut self) -> Option<I::Item> { (**self).next() }
2566     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2567     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2568         (**self).nth(n)
2569     }
2570 }