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