1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse};
14 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev};
15 use super::{Zip, Sum, Product};
16 use super::{ChainState, FromIterator, ZipImpl};
18 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
20 /// An interface for dealing with iterators.
22 /// This is the main iterator trait. For more about the concept of iterators
23 /// generally, please see the [module-level documentation]. In particular, you
24 /// may want to know how to [implement `Iterator`][impl].
26 /// [module-level documentation]: index.html
27 /// [impl]: index.html#implementing-iterator
28 #[stable(feature = "rust1", since = "1.0.0")]
29 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
30 `.iter()` or a similar method"]
32 /// The type of the elements being iterated over.
33 #[stable(feature = "rust1", since = "1.0.0")]
36 /// Advances the iterator and returns the next value.
38 /// Returns [`None`] when iteration is finished. Individual iterator
39 /// implementations may choose to resume iteration, and so calling `next()`
40 /// again may or may not eventually start returning [`Some(Item)`] again at some
43 /// [`None`]: ../../std/option/enum.Option.html#variant.None
44 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
51 /// let a = [1, 2, 3];
53 /// let mut iter = a.iter();
55 /// // A call to next() returns the next value...
56 /// assert_eq!(Some(&1), iter.next());
57 /// assert_eq!(Some(&2), iter.next());
58 /// assert_eq!(Some(&3), iter.next());
60 /// // ... and then None once it's over.
61 /// assert_eq!(None, iter.next());
63 /// // More calls may or may not return None. Here, they always will.
64 /// assert_eq!(None, iter.next());
65 /// assert_eq!(None, iter.next());
67 #[stable(feature = "rust1", since = "1.0.0")]
68 fn next(&mut self) -> Option<Self::Item>;
70 /// Returns the bounds on the remaining length of the iterator.
72 /// Specifically, `size_hint()` returns a tuple where the first element
73 /// is the lower bound, and the second element is the upper bound.
75 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
76 /// A [`None`] here means that either there is no known upper bound, or the
77 /// upper bound is larger than [`usize`].
79 /// # Implementation notes
81 /// It is not enforced that an iterator implementation yields the declared
82 /// number of elements. A buggy iterator may yield less than the lower bound
83 /// or more than the upper bound of elements.
85 /// `size_hint()` is primarily intended to be used for optimizations such as
86 /// reserving space for the elements of the iterator, but must not be
87 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
88 /// implementation of `size_hint()` should not lead to memory safety
91 /// That said, the implementation should provide a correct estimation,
92 /// because otherwise it would be a violation of the trait's protocol.
94 /// The default implementation returns `(0, None)` which is correct for any
97 /// [`usize`]: ../../std/primitive.usize.html
98 /// [`Option`]: ../../std/option/enum.Option.html
99 /// [`None`]: ../../std/option/enum.Option.html#variant.None
106 /// let a = [1, 2, 3];
107 /// let iter = a.iter();
109 /// assert_eq!((3, Some(3)), iter.size_hint());
112 /// A more complex example:
115 /// // The even numbers from zero to ten.
116 /// let iter = (0..10).filter(|x| x % 2 == 0);
118 /// // We might iterate from zero to ten times. Knowing that it's five
119 /// // exactly wouldn't be possible without executing filter().
120 /// assert_eq!((0, Some(10)), iter.size_hint());
122 /// // Let's add one five more numbers with chain()
123 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
125 /// // now both bounds are increased by five
126 /// assert_eq!((5, Some(15)), iter.size_hint());
129 /// Returning `None` for an upper bound:
132 /// // an infinite iterator has no upper bound
135 /// assert_eq!((0, None), iter.size_hint());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
141 /// Consumes the iterator, counting the number of iterations and returning it.
143 /// This method will evaluate the iterator until its [`next`] returns
144 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
145 /// times it called [`next`].
147 /// [`next`]: #tymethod.next
148 /// [`None`]: ../../std/option/enum.Option.html#variant.None
150 /// # Overflow Behavior
152 /// The method does no guarding against overflows, so counting elements of
153 /// an iterator with more than [`usize::MAX`] elements either produces the
154 /// wrong result or panics. If debug assertions are enabled, a panic is
159 /// This function might panic if the iterator has more than [`usize::MAX`]
162 /// [`usize::MAX`]: ../../std/isize/constant.MAX.html
169 /// let a = [1, 2, 3];
170 /// assert_eq!(a.iter().count(), 3);
172 /// let a = [1, 2, 3, 4, 5];
173 /// assert_eq!(a.iter().count(), 5);
176 #[rustc_inherit_overflow_checks]
177 #[stable(feature = "rust1", since = "1.0.0")]
178 fn count(self) -> usize where Self: Sized {
180 self.fold(0, |cnt, _| cnt + 1)
183 /// Consumes the iterator, returning the last element.
185 /// This method will evaluate the iterator until it returns [`None`]. While
186 /// doing so, it keeps track of the current element. After [`None`] is
187 /// returned, `last()` will then return the last element it saw.
189 /// [`None`]: ../../std/option/enum.Option.html#variant.None
196 /// let a = [1, 2, 3];
197 /// assert_eq!(a.iter().last(), Some(&3));
199 /// let a = [1, 2, 3, 4, 5];
200 /// assert_eq!(a.iter().last(), Some(&5));
203 #[stable(feature = "rust1", since = "1.0.0")]
204 fn last(self) -> Option<Self::Item> where Self: Sized {
206 for x in self { last = Some(x); }
210 /// Returns the `n`th element of the iterator.
212 /// Like most indexing operations, the count starts from zero, so `nth(0)`
213 /// returns the first value, `nth(1)` the second, and so on.
215 /// Note that all preceding elements, as well as the returned element, will be
216 /// consumed from the iterator. That means that the preceding elements will be
217 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
218 /// will return different elements.
220 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
223 /// [`None`]: ../../std/option/enum.Option.html#variant.None
230 /// let a = [1, 2, 3];
231 /// assert_eq!(a.iter().nth(1), Some(&2));
234 /// Calling `nth()` multiple times doesn't rewind the iterator:
237 /// let a = [1, 2, 3];
239 /// let mut iter = a.iter();
241 /// assert_eq!(iter.nth(1), Some(&2));
242 /// assert_eq!(iter.nth(1), None);
245 /// Returning `None` if there are less than `n + 1` elements:
248 /// let a = [1, 2, 3];
249 /// assert_eq!(a.iter().nth(10), None);
252 #[stable(feature = "rust1", since = "1.0.0")]
253 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
255 if n == 0 { return Some(x) }
261 /// Takes two iterators and creates a new iterator over both in sequence.
263 /// `chain()` will return a new iterator which will first iterate over
264 /// values from the first iterator and then over values from the second
267 /// In other words, it links two iterators together, in a chain. 🔗
274 /// let a1 = [1, 2, 3];
275 /// let a2 = [4, 5, 6];
277 /// let mut iter = a1.iter().chain(a2.iter());
279 /// assert_eq!(iter.next(), Some(&1));
280 /// assert_eq!(iter.next(), Some(&2));
281 /// assert_eq!(iter.next(), Some(&3));
282 /// assert_eq!(iter.next(), Some(&4));
283 /// assert_eq!(iter.next(), Some(&5));
284 /// assert_eq!(iter.next(), Some(&6));
285 /// assert_eq!(iter.next(), None);
288 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
289 /// anything that can be converted into an [`Iterator`], not just an
290 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
291 /// [`IntoIterator`], and so can be passed to `chain()` directly:
293 /// [`IntoIterator`]: trait.IntoIterator.html
294 /// [`Iterator`]: trait.Iterator.html
297 /// let s1 = &[1, 2, 3];
298 /// let s2 = &[4, 5, 6];
300 /// let mut iter = s1.iter().chain(s2);
302 /// assert_eq!(iter.next(), Some(&1));
303 /// assert_eq!(iter.next(), Some(&2));
304 /// assert_eq!(iter.next(), Some(&3));
305 /// assert_eq!(iter.next(), Some(&4));
306 /// assert_eq!(iter.next(), Some(&5));
307 /// assert_eq!(iter.next(), Some(&6));
308 /// assert_eq!(iter.next(), None);
311 #[stable(feature = "rust1", since = "1.0.0")]
312 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
313 Self: Sized, U: IntoIterator<Item=Self::Item>,
315 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
318 /// 'Zips up' two iterators into a single iterator of pairs.
320 /// `zip()` returns a new iterator that will iterate over two other
321 /// iterators, returning a tuple where the first element comes from the
322 /// first iterator, and the second element comes from the second iterator.
324 /// In other words, it zips two iterators together, into a single one.
326 /// When either iterator returns [`None`], all further calls to [`next`]
327 /// will return [`None`].
334 /// let a1 = [1, 2, 3];
335 /// let a2 = [4, 5, 6];
337 /// let mut iter = a1.iter().zip(a2.iter());
339 /// assert_eq!(iter.next(), Some((&1, &4)));
340 /// assert_eq!(iter.next(), Some((&2, &5)));
341 /// assert_eq!(iter.next(), Some((&3, &6)));
342 /// assert_eq!(iter.next(), None);
345 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
346 /// anything that can be converted into an [`Iterator`], not just an
347 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
348 /// [`IntoIterator`], and so can be passed to `zip()` directly:
350 /// [`IntoIterator`]: trait.IntoIterator.html
351 /// [`Iterator`]: trait.Iterator.html
354 /// let s1 = &[1, 2, 3];
355 /// let s2 = &[4, 5, 6];
357 /// let mut iter = s1.iter().zip(s2);
359 /// assert_eq!(iter.next(), Some((&1, &4)));
360 /// assert_eq!(iter.next(), Some((&2, &5)));
361 /// assert_eq!(iter.next(), Some((&3, &6)));
362 /// assert_eq!(iter.next(), None);
365 /// `zip()` is often used to zip an infinite iterator to a finite one.
366 /// This works because the finite iterator will eventually return [`None`],
367 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
370 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
372 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
374 /// assert_eq!((0, 'f'), enumerate[0]);
375 /// assert_eq!((0, 'f'), zipper[0]);
377 /// assert_eq!((1, 'o'), enumerate[1]);
378 /// assert_eq!((1, 'o'), zipper[1]);
380 /// assert_eq!((2, 'o'), enumerate[2]);
381 /// assert_eq!((2, 'o'), zipper[2]);
384 /// [`enumerate`]: trait.Iterator.html#method.enumerate
385 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
386 /// [`None`]: ../../std/option/enum.Option.html#variant.None
388 #[stable(feature = "rust1", since = "1.0.0")]
389 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
390 Self: Sized, U: IntoIterator
392 Zip::new(self, other.into_iter())
395 /// Takes a closure and creates an iterator which calls that closure on each
398 /// `map()` transforms one iterator into another, by means of its argument:
399 /// something that implements `FnMut`. It produces a new iterator which
400 /// calls this closure on each element of the original iterator.
402 /// If you are good at thinking in types, you can think of `map()` like this:
403 /// If you have an iterator that gives you elements of some type `A`, and
404 /// you want an iterator of some other type `B`, you can use `map()`,
405 /// passing a closure that takes an `A` and returns a `B`.
407 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
408 /// lazy, it is best used when you're already working with other iterators.
409 /// If you're doing some sort of looping for a side effect, it's considered
410 /// more idiomatic to use [`for`] than `map()`.
412 /// [`for`]: ../../book/first-edition/loops.html#for
419 /// let a = [1, 2, 3];
421 /// let mut iter = a.into_iter().map(|x| 2 * x);
423 /// assert_eq!(iter.next(), Some(2));
424 /// assert_eq!(iter.next(), Some(4));
425 /// assert_eq!(iter.next(), Some(6));
426 /// assert_eq!(iter.next(), None);
429 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
432 /// # #![allow(unused_must_use)]
433 /// // don't do this:
434 /// (0..5).map(|x| println!("{}", x));
436 /// // it won't even execute, as it is lazy. Rust will warn you about this.
438 /// // Instead, use for:
440 /// println!("{}", x);
444 #[stable(feature = "rust1", since = "1.0.0")]
445 fn map<B, F>(self, f: F) -> Map<Self, F> where
446 Self: Sized, F: FnMut(Self::Item) -> B,
448 Map{iter: self, f: f}
451 /// Creates an iterator which uses a closure to determine if an element
452 /// should be yielded.
454 /// The closure must return `true` or `false`. `filter()` creates an
455 /// iterator which calls this closure on each element. If the closure
456 /// returns `true`, then the element is returned. If the closure returns
457 /// `false`, it will try again, and call the closure on the next element,
458 /// seeing if it passes the test.
465 /// let a = [0i32, 1, 2];
467 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
469 /// assert_eq!(iter.next(), Some(&1));
470 /// assert_eq!(iter.next(), Some(&2));
471 /// assert_eq!(iter.next(), None);
474 /// Because the closure passed to `filter()` takes a reference, and many
475 /// iterators iterate over references, this leads to a possibly confusing
476 /// situation, where the type of the closure is a double reference:
479 /// let a = [0, 1, 2];
481 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
483 /// assert_eq!(iter.next(), Some(&2));
484 /// assert_eq!(iter.next(), None);
487 /// It's common to instead use destructuring on the argument to strip away
491 /// let a = [0, 1, 2];
493 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
495 /// assert_eq!(iter.next(), Some(&2));
496 /// assert_eq!(iter.next(), None);
502 /// let a = [0, 1, 2];
504 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
506 /// assert_eq!(iter.next(), Some(&2));
507 /// assert_eq!(iter.next(), None);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
514 Self: Sized, P: FnMut(&Self::Item) -> bool,
516 Filter{iter: self, predicate: predicate}
519 /// Creates an iterator that both filters and maps.
521 /// The closure must return an [`Option<T>`]. `filter_map` creates an
522 /// iterator which calls this closure on each element. If the closure
523 /// returns [`Some(element)`][`Some`], then that element is returned. If the
524 /// closure returns [`None`], it will try again, and call the closure on the
525 /// next element, seeing if it will return [`Some`].
527 /// Why `filter_map` and not just [`filter`].[`map`]? The key is in this
530 /// [`filter`]: #method.filter
531 /// [`map`]: #method.map
533 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
535 /// In other words, it removes the [`Option<T>`] layer automatically. If your
536 /// mapping is already returning an [`Option<T>`] and you want to skip over
537 /// [`None`]s, then `filter_map` is much, much nicer to use.
544 /// let a = ["1", "2", "lol"];
546 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
548 /// assert_eq!(iter.next(), Some(1));
549 /// assert_eq!(iter.next(), Some(2));
550 /// assert_eq!(iter.next(), None);
553 /// Here's the same example, but with [`filter`] and [`map`]:
556 /// let a = ["1", "2", "lol"];
558 /// let mut iter = a.iter()
559 /// .map(|s| s.parse().ok())
560 /// .filter(|s| s.is_some());
562 /// assert_eq!(iter.next(), Some(Some(1)));
563 /// assert_eq!(iter.next(), Some(Some(2)));
564 /// assert_eq!(iter.next(), None);
567 /// There's an extra layer of [`Some`] in there.
569 /// [`Option<T>`]: ../../std/option/enum.Option.html
570 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
571 /// [`None`]: ../../std/option/enum.Option.html#variant.None
573 #[stable(feature = "rust1", since = "1.0.0")]
574 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
575 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
577 FilterMap { iter: self, f: f }
580 /// Creates an iterator which gives the current iteration count as well as
583 /// The iterator returned yields pairs `(i, val)`, where `i` is the
584 /// current index of iteration and `val` is the value returned by the
587 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
588 /// different sized integer, the [`zip`] function provides similar
591 /// # Overflow Behavior
593 /// The method does no guarding against overflows, so enumerating more than
594 /// [`usize::MAX`] elements either produces the wrong result or panics. If
595 /// debug assertions are enabled, a panic is guaranteed.
599 /// The returned iterator might panic if the to-be-returned index would
600 /// overflow a [`usize`].
602 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
603 /// [`usize`]: ../../std/primitive.usize.html
604 /// [`zip`]: #method.zip
609 /// let a = ['a', 'b', 'c'];
611 /// let mut iter = a.iter().enumerate();
613 /// assert_eq!(iter.next(), Some((0, &'a')));
614 /// assert_eq!(iter.next(), Some((1, &'b')));
615 /// assert_eq!(iter.next(), Some((2, &'c')));
616 /// assert_eq!(iter.next(), None);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
621 Enumerate { iter: self, count: 0 }
624 /// Creates an iterator which can use `peek` to look at the next element of
625 /// the iterator without consuming it.
627 /// Adds a [`peek`] method to an iterator. See its documentation for
628 /// more information.
630 /// Note that the underlying iterator is still advanced when [`peek`] is
631 /// called for the first time: In order to retrieve the next element,
632 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
633 /// anything other than fetching the next value) of the [`next`] method
636 /// [`peek`]: struct.Peekable.html#method.peek
637 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
644 /// let xs = [1, 2, 3];
646 /// let mut iter = xs.iter().peekable();
648 /// // peek() lets us see into the future
649 /// assert_eq!(iter.peek(), Some(&&1));
650 /// assert_eq!(iter.next(), Some(&1));
652 /// assert_eq!(iter.next(), Some(&2));
654 /// // we can peek() multiple times, the iterator won't advance
655 /// assert_eq!(iter.peek(), Some(&&3));
656 /// assert_eq!(iter.peek(), Some(&&3));
658 /// assert_eq!(iter.next(), Some(&3));
660 /// // after the iterator is finished, so is peek()
661 /// assert_eq!(iter.peek(), None);
662 /// assert_eq!(iter.next(), None);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 fn peekable(self) -> Peekable<Self> where Self: Sized {
667 Peekable{iter: self, peeked: None}
670 /// Creates an iterator that [`skip`]s elements based on a predicate.
672 /// [`skip`]: #method.skip
674 /// `skip_while()` takes a closure as an argument. It will call this
675 /// closure on each element of the iterator, and ignore elements
676 /// until it returns `false`.
678 /// After `false` is returned, `skip_while()`'s job is over, and the
679 /// rest of the elements are yielded.
686 /// let a = [-1i32, 0, 1];
688 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
690 /// assert_eq!(iter.next(), Some(&0));
691 /// assert_eq!(iter.next(), Some(&1));
692 /// assert_eq!(iter.next(), None);
695 /// Because the closure passed to `skip_while()` takes a reference, and many
696 /// iterators iterate over references, this leads to a possibly confusing
697 /// situation, where the type of the closure is a double reference:
700 /// let a = [-1, 0, 1];
702 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
704 /// assert_eq!(iter.next(), Some(&0));
705 /// assert_eq!(iter.next(), Some(&1));
706 /// assert_eq!(iter.next(), None);
709 /// Stopping after an initial `false`:
712 /// let a = [-1, 0, 1, -2];
714 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
716 /// assert_eq!(iter.next(), Some(&0));
717 /// assert_eq!(iter.next(), Some(&1));
719 /// // while this would have been false, since we already got a false,
720 /// // skip_while() isn't used any more
721 /// assert_eq!(iter.next(), Some(&-2));
723 /// assert_eq!(iter.next(), None);
726 #[stable(feature = "rust1", since = "1.0.0")]
727 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
728 Self: Sized, P: FnMut(&Self::Item) -> bool,
730 SkipWhile{iter: self, flag: false, predicate: predicate}
733 /// Creates an iterator that yields elements based on a predicate.
735 /// `take_while()` takes a closure as an argument. It will call this
736 /// closure on each element of the iterator, and yield elements
737 /// while it returns `true`.
739 /// After `false` is returned, `take_while()`'s job is over, and the
740 /// rest of the elements are ignored.
747 /// let a = [-1i32, 0, 1];
749 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
751 /// assert_eq!(iter.next(), Some(&-1));
752 /// assert_eq!(iter.next(), None);
755 /// Because the closure passed to `take_while()` takes a reference, and many
756 /// iterators iterate over references, this leads to a possibly confusing
757 /// situation, where the type of the closure is a double reference:
760 /// let a = [-1, 0, 1];
762 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
764 /// assert_eq!(iter.next(), Some(&-1));
765 /// assert_eq!(iter.next(), None);
768 /// Stopping after an initial `false`:
771 /// let a = [-1, 0, 1, -2];
773 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
775 /// assert_eq!(iter.next(), Some(&-1));
777 /// // We have more elements that are less than zero, but since we already
778 /// // got a false, take_while() isn't used any more
779 /// assert_eq!(iter.next(), None);
782 /// Because `take_while()` needs to look at the value in order to see if it
783 /// should be included or not, consuming iterators will see that it is
787 /// let a = [1, 2, 3, 4];
788 /// let mut iter = a.into_iter();
790 /// let result: Vec<i32> = iter.by_ref()
791 /// .take_while(|n| **n != 3)
795 /// assert_eq!(result, &[1, 2]);
797 /// let result: Vec<i32> = iter.cloned().collect();
799 /// assert_eq!(result, &[4]);
802 /// The `3` is no longer there, because it was consumed in order to see if
803 /// the iteration should stop, but wasn't placed back into the iterator or
804 /// some similar thing.
806 #[stable(feature = "rust1", since = "1.0.0")]
807 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
808 Self: Sized, P: FnMut(&Self::Item) -> bool,
810 TakeWhile{iter: self, flag: false, predicate: predicate}
813 /// Creates an iterator that skips the first `n` elements.
815 /// After they have been consumed, the rest of the elements are yielded.
822 /// let a = [1, 2, 3];
824 /// let mut iter = a.iter().skip(2);
826 /// assert_eq!(iter.next(), Some(&3));
827 /// assert_eq!(iter.next(), None);
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
832 Skip{iter: self, n: n}
835 /// Creates an iterator that yields its first `n` elements.
842 /// let a = [1, 2, 3];
844 /// let mut iter = a.iter().take(2);
846 /// assert_eq!(iter.next(), Some(&1));
847 /// assert_eq!(iter.next(), Some(&2));
848 /// assert_eq!(iter.next(), None);
851 /// `take()` is often used with an infinite iterator, to make it finite:
854 /// let mut iter = (0..).take(3);
856 /// assert_eq!(iter.next(), Some(0));
857 /// assert_eq!(iter.next(), Some(1));
858 /// assert_eq!(iter.next(), Some(2));
859 /// assert_eq!(iter.next(), None);
862 #[stable(feature = "rust1", since = "1.0.0")]
863 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
864 Take{iter: self, n: n}
867 /// An iterator adaptor similar to [`fold`] that holds internal state and
868 /// produces a new iterator.
870 /// [`fold`]: #method.fold
872 /// `scan()` takes two arguments: an initial value which seeds the internal
873 /// state, and a closure with two arguments, the first being a mutable
874 /// reference to the internal state and the second an iterator element.
875 /// The closure can assign to the internal state to share state between
878 /// On iteration, the closure will be applied to each element of the
879 /// iterator and the return value from the closure, an [`Option`], is
880 /// yielded by the iterator.
882 /// [`Option`]: ../../std/option/enum.Option.html
889 /// let a = [1, 2, 3];
891 /// let mut iter = a.iter().scan(1, |state, &x| {
892 /// // each iteration, we'll multiply the state by the element
893 /// *state = *state * x;
895 /// // the value passed on to the next iteration
899 /// assert_eq!(iter.next(), Some(1));
900 /// assert_eq!(iter.next(), Some(2));
901 /// assert_eq!(iter.next(), Some(6));
902 /// assert_eq!(iter.next(), None);
905 #[stable(feature = "rust1", since = "1.0.0")]
906 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
907 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
909 Scan{iter: self, f: f, state: initial_state}
912 /// Creates an iterator that works like map, but flattens nested structure.
914 /// The [`map`] adapter is very useful, but only when the closure
915 /// argument produces values. If it produces an iterator instead, there's
916 /// an extra layer of indirection. `flat_map()` will remove this extra layer
919 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
920 /// one item for each element, and `flat_map()`'s closure returns an
921 /// iterator for each element.
923 /// [`map`]: #method.map
930 /// let words = ["alpha", "beta", "gamma"];
932 /// // chars() returns an iterator
933 /// let merged: String = words.iter()
934 /// .flat_map(|s| s.chars())
936 /// assert_eq!(merged, "alphabetagamma");
939 #[stable(feature = "rust1", since = "1.0.0")]
940 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
941 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
943 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
946 /// Creates an iterator which ends after the first [`None`].
948 /// After an iterator returns [`None`], future calls may or may not yield
949 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
950 /// [`None`] is given, it will always return [`None`] forever.
952 /// [`None`]: ../../std/option/enum.Option.html#variant.None
953 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
960 /// // an iterator which alternates between Some and None
961 /// struct Alternate {
965 /// impl Iterator for Alternate {
968 /// fn next(&mut self) -> Option<i32> {
969 /// let val = self.state;
970 /// self.state = self.state + 1;
972 /// // if it's even, Some(i32), else None
973 /// if val % 2 == 0 {
981 /// let mut iter = Alternate { state: 0 };
983 /// // we can see our iterator going back and forth
984 /// assert_eq!(iter.next(), Some(0));
985 /// assert_eq!(iter.next(), None);
986 /// assert_eq!(iter.next(), Some(2));
987 /// assert_eq!(iter.next(), None);
989 /// // however, once we fuse it...
990 /// let mut iter = iter.fuse();
992 /// assert_eq!(iter.next(), Some(4));
993 /// assert_eq!(iter.next(), None);
995 /// // it will always return None after the first time.
996 /// assert_eq!(iter.next(), None);
997 /// assert_eq!(iter.next(), None);
998 /// assert_eq!(iter.next(), None);
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 fn fuse(self) -> Fuse<Self> where Self: Sized {
1003 Fuse{iter: self, done: false}
1006 /// Do something with each element of an iterator, passing the value on.
1008 /// When using iterators, you'll often chain several of them together.
1009 /// While working on such code, you might want to check out what's
1010 /// happening at various parts in the pipeline. To do that, insert
1011 /// a call to `inspect()`.
1013 /// It's much more common for `inspect()` to be used as a debugging tool
1014 /// than to exist in your final code, but never say never.
1021 /// let a = [1, 4, 2, 3];
1023 /// // this iterator sequence is complex.
1024 /// let sum = a.iter()
1026 /// .filter(|&x| x % 2 == 0)
1027 /// .fold(0, |sum, i| sum + i);
1029 /// println!("{}", sum);
1031 /// // let's add some inspect() calls to investigate what's happening
1032 /// let sum = a.iter()
1034 /// .inspect(|x| println!("about to filter: {}", x))
1035 /// .filter(|&x| x % 2 == 0)
1036 /// .inspect(|x| println!("made it through filter: {}", x))
1037 /// .fold(0, |sum, i| sum + i);
1039 /// println!("{}", sum);
1042 /// This will print:
1045 /// about to filter: 1
1046 /// about to filter: 4
1047 /// made it through filter: 4
1048 /// about to filter: 2
1049 /// made it through filter: 2
1050 /// about to filter: 3
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1056 Self: Sized, F: FnMut(&Self::Item),
1058 Inspect{iter: self, f: f}
1061 /// Borrows an iterator, rather than consuming it.
1063 /// This is useful to allow applying iterator adaptors while still
1064 /// retaining ownership of the original iterator.
1071 /// let a = [1, 2, 3];
1073 /// let iter = a.into_iter();
1075 /// let sum: i32 = iter.take(5)
1076 /// .fold(0, |acc, &i| acc + i );
1078 /// assert_eq!(sum, 6);
1080 /// // if we try to use iter again, it won't work. The following line
1081 /// // gives "error: use of moved value: `iter`
1082 /// // assert_eq!(iter.next(), None);
1084 /// // let's try that again
1085 /// let a = [1, 2, 3];
1087 /// let mut iter = a.into_iter();
1089 /// // instead, we add in a .by_ref()
1090 /// let sum: i32 = iter.by_ref()
1092 /// .fold(0, |acc, &i| acc + i );
1094 /// assert_eq!(sum, 3);
1096 /// // now this is just fine:
1097 /// assert_eq!(iter.next(), Some(&3));
1098 /// assert_eq!(iter.next(), None);
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1103 /// Transforms an iterator into a collection.
1105 /// `collect()` can take anything iterable, and turn it into a relevant
1106 /// collection. This is one of the more powerful methods in the standard
1107 /// library, used in a variety of contexts.
1109 /// The most basic pattern in which `collect()` is used is to turn one
1110 /// collection into another. You take a collection, call [`iter`] on it,
1111 /// do a bunch of transformations, and then `collect()` at the end.
1113 /// One of the keys to `collect()`'s power is that many things you might
1114 /// not think of as 'collections' actually are. For example, a [`String`]
1115 /// is a collection of [`char`]s. And a collection of
1116 /// [`Result<T, E>`][`Result`] can be thought of as single
1117 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1119 /// Because `collect()` is so general, it can cause problems with type
1120 /// inference. As such, `collect()` is one of the few times you'll see
1121 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1122 /// helps the inference algorithm understand specifically which collection
1123 /// you're trying to collect into.
1130 /// let a = [1, 2, 3];
1132 /// let doubled: Vec<i32> = a.iter()
1133 /// .map(|&x| x * 2)
1136 /// assert_eq!(vec![2, 4, 6], doubled);
1139 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1140 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1142 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1145 /// use std::collections::VecDeque;
1147 /// let a = [1, 2, 3];
1149 /// let doubled: VecDeque<i32> = a.iter()
1150 /// .map(|&x| x * 2)
1153 /// assert_eq!(2, doubled[0]);
1154 /// assert_eq!(4, doubled[1]);
1155 /// assert_eq!(6, doubled[2]);
1158 /// Using the 'turbofish' instead of annotating `doubled`:
1161 /// let a = [1, 2, 3];
1163 /// let doubled = a.iter()
1164 /// .map(|&x| x * 2)
1165 /// .collect::<Vec<i32>>();
1167 /// assert_eq!(vec![2, 4, 6], doubled);
1170 /// Because `collect()` cares about what you're collecting into, you can
1171 /// still use a partial type hint, `_`, with the turbofish:
1174 /// let a = [1, 2, 3];
1176 /// let doubled = a.iter()
1177 /// .map(|&x| x * 2)
1178 /// .collect::<Vec<_>>();
1180 /// assert_eq!(vec![2, 4, 6], doubled);
1183 /// Using `collect()` to make a [`String`]:
1186 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1188 /// let hello: String = chars.iter()
1189 /// .map(|&x| x as u8)
1190 /// .map(|x| (x + 1) as char)
1193 /// assert_eq!("hello", hello);
1196 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1197 /// see if any of them failed:
1200 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1202 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1204 /// // gives us the first error
1205 /// assert_eq!(Err("nope"), result);
1207 /// let results = [Ok(1), Ok(3)];
1209 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1211 /// // gives us the list of answers
1212 /// assert_eq!(Ok(vec![1, 3]), result);
1215 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1216 /// [`String`]: ../../std/string/struct.String.html
1217 /// [`char`]: ../../std/primitive.char.html
1218 /// [`Result`]: ../../std/result/enum.Result.html
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1222 FromIterator::from_iter(self)
1225 /// Consumes an iterator, creating two collections from it.
1227 /// The predicate passed to `partition()` can return `true`, or `false`.
1228 /// `partition()` returns a pair, all of the elements for which it returned
1229 /// `true`, and all of the elements for which it returned `false`.
1236 /// let a = [1, 2, 3];
1238 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1239 /// .partition(|&n| n % 2 == 0);
1241 /// assert_eq!(even, vec![2]);
1242 /// assert_eq!(odd, vec![1, 3]);
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 fn partition<B, F>(self, mut f: F) -> (B, B) where
1247 B: Default + Extend<Self::Item>,
1248 F: FnMut(&Self::Item) -> bool
1250 let mut left: B = Default::default();
1251 let mut right: B = Default::default();
1255 left.extend(Some(x))
1257 right.extend(Some(x))
1264 /// An iterator adaptor that applies a function, producing a single, final value.
1266 /// `fold()` takes two arguments: an initial value, and a closure with two
1267 /// arguments: an 'accumulator', and an element. The closure returns the value that
1268 /// the accumulator should have for the next iteration.
1270 /// The initial value is the value the accumulator will have on the first
1273 /// After applying this closure to every element of the iterator, `fold()`
1274 /// returns the accumulator.
1276 /// This operation is sometimes called 'reduce' or 'inject'.
1278 /// Folding is useful whenever you have a collection of something, and want
1279 /// to produce a single value from it.
1286 /// let a = [1, 2, 3];
1288 /// // the sum of all of the elements of a
1289 /// let sum = a.iter()
1290 /// .fold(0, |acc, &x| acc + x);
1292 /// assert_eq!(sum, 6);
1295 /// Let's walk through each step of the iteration here:
1297 /// | element | acc | x | result |
1298 /// |---------|-----|---|--------|
1300 /// | 1 | 0 | 1 | 1 |
1301 /// | 2 | 1 | 2 | 3 |
1302 /// | 3 | 3 | 3 | 6 |
1304 /// And so, our final result, `6`.
1306 /// It's common for people who haven't used iterators a lot to
1307 /// use a `for` loop with a list of things to build up a result. Those
1308 /// can be turned into `fold()`s:
1310 /// [`for`]: ../../book/first-edition/loops.html#for
1313 /// let numbers = [1, 2, 3, 4, 5];
1315 /// let mut result = 0;
1318 /// for i in &numbers {
1319 /// result = result + i;
1323 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1325 /// // they're the same
1326 /// assert_eq!(result, result2);
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 fn fold<B, F>(self, init: B, mut f: F) -> B where
1331 Self: Sized, F: FnMut(B, Self::Item) -> B,
1333 let mut accum = init;
1335 accum = f(accum, x);
1340 /// Tests if every element of the iterator matches a predicate.
1342 /// `all()` takes a closure that returns `true` or `false`. It applies
1343 /// this closure to each element of the iterator, and if they all return
1344 /// `true`, then so does `all()`. If any of them return `false`, it
1345 /// returns `false`.
1347 /// `all()` is short-circuiting; in other words, it will stop processing
1348 /// as soon as it finds a `false`, given that no matter what else happens,
1349 /// the result will also be `false`.
1351 /// An empty iterator returns `true`.
1358 /// let a = [1, 2, 3];
1360 /// assert!(a.iter().all(|&x| x > 0));
1362 /// assert!(!a.iter().all(|&x| x > 2));
1365 /// Stopping at the first `false`:
1368 /// let a = [1, 2, 3];
1370 /// let mut iter = a.iter();
1372 /// assert!(!iter.all(|&x| x != 2));
1374 /// // we can still use `iter`, as there are more elements.
1375 /// assert_eq!(iter.next(), Some(&3));
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 fn all<F>(&mut self, mut f: F) -> bool where
1380 Self: Sized, F: FnMut(Self::Item) -> bool
1390 /// Tests if any element of the iterator matches a predicate.
1392 /// `any()` takes a closure that returns `true` or `false`. It applies
1393 /// this closure to each element of the iterator, and if any of them return
1394 /// `true`, then so does `any()`. If they all return `false`, it
1395 /// returns `false`.
1397 /// `any()` is short-circuiting; in other words, it will stop processing
1398 /// as soon as it finds a `true`, given that no matter what else happens,
1399 /// the result will also be `true`.
1401 /// An empty iterator returns `false`.
1408 /// let a = [1, 2, 3];
1410 /// assert!(a.iter().any(|&x| x > 0));
1412 /// assert!(!a.iter().any(|&x| x > 5));
1415 /// Stopping at the first `true`:
1418 /// let a = [1, 2, 3];
1420 /// let mut iter = a.iter();
1422 /// assert!(iter.any(|&x| x != 2));
1424 /// // we can still use `iter`, as there are more elements.
1425 /// assert_eq!(iter.next(), Some(&2));
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 fn any<F>(&mut self, mut f: F) -> bool where
1431 F: FnMut(Self::Item) -> bool
1441 /// Searches for an element of an iterator that satisfies a predicate.
1443 /// `find()` takes a closure that returns `true` or `false`. It applies
1444 /// this closure to each element of the iterator, and if any of them return
1445 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1446 /// `false`, it returns [`None`].
1448 /// `find()` is short-circuiting; in other words, it will stop processing
1449 /// as soon as the closure returns `true`.
1451 /// Because `find()` takes a reference, and many iterators iterate over
1452 /// references, this leads to a possibly confusing situation where the
1453 /// argument is a double reference. You can see this effect in the
1454 /// examples below, with `&&x`.
1456 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1457 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1464 /// let a = [1, 2, 3];
1466 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1468 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1471 /// Stopping at the first `true`:
1474 /// let a = [1, 2, 3];
1476 /// let mut iter = a.iter();
1478 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1480 /// // we can still use `iter`, as there are more elements.
1481 /// assert_eq!(iter.next(), Some(&3));
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1487 P: FnMut(&Self::Item) -> bool,
1490 if predicate(&x) { return Some(x) }
1495 /// Searches for an element in an iterator, returning its index.
1497 /// `position()` takes a closure that returns `true` or `false`. It applies
1498 /// this closure to each element of the iterator, and if one of them
1499 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1500 /// them return `false`, it returns [`None`].
1502 /// `position()` is short-circuiting; in other words, it will stop
1503 /// processing as soon as it finds a `true`.
1505 /// # Overflow Behavior
1507 /// The method does no guarding against overflows, so if there are more
1508 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1509 /// result or panics. If debug assertions are enabled, a panic is
1514 /// This function might panic if the iterator has more than `usize::MAX`
1515 /// non-matching elements.
1517 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1518 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1519 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1526 /// let a = [1, 2, 3];
1528 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1530 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1533 /// Stopping at the first `true`:
1536 /// let a = [1, 2, 3, 4];
1538 /// let mut iter = a.iter();
1540 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1542 /// // we can still use `iter`, as there are more elements.
1543 /// assert_eq!(iter.next(), Some(&3));
1545 /// // The returned index depends on iterator state
1546 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1553 P: FnMut(Self::Item) -> bool,
1555 // `enumerate` might overflow.
1556 for (i, x) in self.enumerate() {
1564 /// Searches for an element in an iterator from the right, returning its
1567 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1568 /// this closure to each element of the iterator, starting from the end,
1569 /// and if one of them returns `true`, then `rposition()` returns
1570 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1572 /// `rposition()` is short-circuiting; in other words, it will stop
1573 /// processing as soon as it finds a `true`.
1575 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1576 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1583 /// let a = [1, 2, 3];
1585 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1587 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1590 /// Stopping at the first `true`:
1593 /// let a = [1, 2, 3];
1595 /// let mut iter = a.iter();
1597 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1599 /// // we can still use `iter`, as there are more elements.
1600 /// assert_eq!(iter.next(), Some(&1));
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1605 P: FnMut(Self::Item) -> bool,
1606 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1608 let mut i = self.len();
1610 while let Some(v) = self.next_back() {
1611 // No need for an overflow check here, because `ExactSizeIterator`
1612 // implies that the number of elements fits into a `usize`.
1621 /// Returns the maximum element of an iterator.
1623 /// If several elements are equally maximum, the last element is
1624 /// returned. If the iterator is empty, [`None`] is returned.
1626 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1633 /// let a = [1, 2, 3];
1634 /// let b: Vec<u32> = Vec::new();
1636 /// assert_eq!(a.iter().max(), Some(&3));
1637 /// assert_eq!(b.iter().max(), None);
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1645 // switch to y even if it is only equal, to preserve
1647 |_, x, _, y| *x <= *y)
1651 /// Returns the minimum element of an iterator.
1653 /// If several elements are equally minimum, the first element is
1654 /// returned. If the iterator is empty, [`None`] is returned.
1656 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1663 /// let a = [1, 2, 3];
1664 /// let b: Vec<u32> = Vec::new();
1666 /// assert_eq!(a.iter().min(), Some(&1));
1667 /// assert_eq!(b.iter().min(), None);
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1675 // only switch to y if it is strictly smaller, to
1676 // preserve stability.
1677 |_, x, _, y| *x > *y)
1681 /// Returns the element that gives the maximum value from the
1682 /// specified function.
1684 /// If several elements are equally maximum, the last element is
1685 /// returned. If the iterator is empty, [`None`] is returned.
1687 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1692 /// let a = [-3_i32, 0, 1, 5, -10];
1693 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1696 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1697 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1698 where Self: Sized, F: FnMut(&Self::Item) -> B,
1702 // switch to y even if it is only equal, to preserve
1704 |x_p, _, y_p, _| x_p <= y_p)
1708 /// Returns the element that gives the maximum value with respect to the
1709 /// specified comparison function.
1711 /// If several elements are equally maximum, the last element is
1712 /// returned. If the iterator is empty, [`None`] is returned.
1714 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1719 /// let a = [-3_i32, 0, 1, 5, -10];
1720 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1723 #[stable(feature = "iter_max_by", since = "1.15.0")]
1724 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1725 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1729 // switch to y even if it is only equal, to preserve
1731 |_, x, _, y| Ordering::Greater != compare(x, y))
1735 /// Returns the element that gives the minimum value from the
1736 /// specified function.
1738 /// If several elements are equally minimum, the first element is
1739 /// returned. If the iterator is empty, [`None`] is returned.
1741 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1746 /// let a = [-3_i32, 0, 1, 5, -10];
1747 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1749 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1750 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1751 where Self: Sized, F: FnMut(&Self::Item) -> B,
1755 // only switch to y if it is strictly smaller, to
1756 // preserve stability.
1757 |x_p, _, y_p, _| x_p > y_p)
1761 /// Returns the element that gives the minimum value with respect to the
1762 /// specified comparison function.
1764 /// If several elements are equally minimum, the first element is
1765 /// returned. If the iterator is empty, [`None`] is returned.
1767 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1772 /// let a = [-3_i32, 0, 1, 5, -10];
1773 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1776 #[stable(feature = "iter_min_by", since = "1.15.0")]
1777 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
1778 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1782 // switch to y even if it is strictly smaller, to
1783 // preserve stability.
1784 |_, x, _, y| Ordering::Greater == compare(x, y))
1789 /// Reverses an iterator's direction.
1791 /// Usually, iterators iterate from left to right. After using `rev()`,
1792 /// an iterator will instead iterate from right to left.
1794 /// This is only possible if the iterator has an end, so `rev()` only
1795 /// works on [`DoubleEndedIterator`]s.
1797 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1802 /// let a = [1, 2, 3];
1804 /// let mut iter = a.iter().rev();
1806 /// assert_eq!(iter.next(), Some(&3));
1807 /// assert_eq!(iter.next(), Some(&2));
1808 /// assert_eq!(iter.next(), Some(&1));
1810 /// assert_eq!(iter.next(), None);
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1818 /// Converts an iterator of pairs into a pair of containers.
1820 /// `unzip()` consumes an entire iterator of pairs, producing two
1821 /// collections: one from the left elements of the pairs, and one
1822 /// from the right elements.
1824 /// This function is, in some sense, the opposite of [`zip`].
1826 /// [`zip`]: #method.zip
1833 /// let a = [(1, 2), (3, 4)];
1835 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1837 /// assert_eq!(left, [1, 3]);
1838 /// assert_eq!(right, [2, 4]);
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1842 FromA: Default + Extend<A>,
1843 FromB: Default + Extend<B>,
1844 Self: Sized + Iterator<Item=(A, B)>,
1846 let mut ts: FromA = Default::default();
1847 let mut us: FromB = Default::default();
1849 for (t, u) in self {
1857 /// Creates an iterator which [`clone`]s all of its elements.
1859 /// This is useful when you have an iterator over `&T`, but you need an
1860 /// iterator over `T`.
1862 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
1869 /// let a = [1, 2, 3];
1871 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1873 /// // cloned is the same as .map(|&x| x), for integers
1874 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1876 /// assert_eq!(v_cloned, vec![1, 2, 3]);
1877 /// assert_eq!(v_map, vec![1, 2, 3]);
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1881 where Self: Sized + Iterator<Item=&'a T>, T: Clone
1886 /// Repeats an iterator endlessly.
1888 /// Instead of stopping at [`None`], the iterator will instead start again,
1889 /// from the beginning. After iterating again, it will start at the
1890 /// beginning again. And again. And again. Forever.
1892 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1899 /// let a = [1, 2, 3];
1901 /// let mut it = a.iter().cycle();
1903 /// assert_eq!(it.next(), Some(&1));
1904 /// assert_eq!(it.next(), Some(&2));
1905 /// assert_eq!(it.next(), Some(&3));
1906 /// assert_eq!(it.next(), Some(&1));
1907 /// assert_eq!(it.next(), Some(&2));
1908 /// assert_eq!(it.next(), Some(&3));
1909 /// assert_eq!(it.next(), Some(&1));
1911 #[stable(feature = "rust1", since = "1.0.0")]
1913 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1914 Cycle{orig: self.clone(), iter: self}
1917 /// Sums the elements of an iterator.
1919 /// Takes each element, adds them together, and returns the result.
1921 /// An empty iterator returns the zero value of the type.
1925 /// When calling `sum()` and a primitive integer type is being returned, this
1926 /// method will panic if the computation overflows and debug assertions are
1934 /// let a = [1, 2, 3];
1935 /// let sum: i32 = a.iter().sum();
1937 /// assert_eq!(sum, 6);
1939 #[stable(feature = "iter_arith", since = "1.11.0")]
1940 fn sum<S>(self) -> S
1947 /// Iterates over the entire iterator, multiplying all the elements
1949 /// An empty iterator returns the one value of the type.
1953 /// When calling `product()` and a primitive integer type is being returned,
1954 /// method will panic if the computation overflows and debug assertions are
1960 /// fn factorial(n: u32) -> u32 {
1961 /// (1..).take_while(|&i| i <= n).product()
1963 /// assert_eq!(factorial(0), 1);
1964 /// assert_eq!(factorial(1), 1);
1965 /// assert_eq!(factorial(5), 120);
1967 #[stable(feature = "iter_arith", since = "1.11.0")]
1968 fn product<P>(self) -> P
1970 P: Product<Self::Item>,
1972 Product::product(self)
1975 /// Lexicographically compares the elements of this `Iterator` with those
1977 #[stable(feature = "iter_order", since = "1.5.0")]
1978 fn cmp<I>(mut self, other: I) -> Ordering where
1979 I: IntoIterator<Item = Self::Item>,
1983 let mut other = other.into_iter();
1986 match (self.next(), other.next()) {
1987 (None, None) => return Ordering::Equal,
1988 (None, _ ) => return Ordering::Less,
1989 (_ , None) => return Ordering::Greater,
1990 (Some(x), Some(y)) => match x.cmp(&y) {
1991 Ordering::Equal => (),
1992 non_eq => return non_eq,
1998 /// Lexicographically compares the elements of this `Iterator` with those
2000 #[stable(feature = "iter_order", since = "1.5.0")]
2001 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2003 Self::Item: PartialOrd<I::Item>,
2006 let mut other = other.into_iter();
2009 match (self.next(), other.next()) {
2010 (None, None) => return Some(Ordering::Equal),
2011 (None, _ ) => return Some(Ordering::Less),
2012 (_ , None) => return Some(Ordering::Greater),
2013 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2014 Some(Ordering::Equal) => (),
2015 non_eq => return non_eq,
2021 /// Determines if the elements of this `Iterator` are equal to those of
2023 #[stable(feature = "iter_order", since = "1.5.0")]
2024 fn eq<I>(mut self, other: I) -> bool where
2026 Self::Item: PartialEq<I::Item>,
2029 let mut other = other.into_iter();
2032 match (self.next(), other.next()) {
2033 (None, None) => return true,
2034 (None, _) | (_, None) => return false,
2035 (Some(x), Some(y)) => if x != y { return false },
2040 /// Determines if the elements of this `Iterator` are unequal to those of
2042 #[stable(feature = "iter_order", since = "1.5.0")]
2043 fn ne<I>(mut self, other: I) -> bool where
2045 Self::Item: PartialEq<I::Item>,
2048 let mut other = other.into_iter();
2051 match (self.next(), other.next()) {
2052 (None, None) => return false,
2053 (None, _) | (_, None) => return true,
2054 (Some(x), Some(y)) => if x.ne(&y) { return true },
2059 /// Determines if the elements of this `Iterator` are lexicographically
2060 /// less than those of another.
2061 #[stable(feature = "iter_order", since = "1.5.0")]
2062 fn lt<I>(mut self, other: I) -> bool where
2064 Self::Item: PartialOrd<I::Item>,
2067 let mut other = other.into_iter();
2070 match (self.next(), other.next()) {
2071 (None, None) => return false,
2072 (None, _ ) => return true,
2073 (_ , None) => return false,
2074 (Some(x), Some(y)) => {
2075 match x.partial_cmp(&y) {
2076 Some(Ordering::Less) => return true,
2077 Some(Ordering::Equal) => {}
2078 Some(Ordering::Greater) => return false,
2079 None => return false,
2086 /// Determines if the elements of this `Iterator` are lexicographically
2087 /// less or equal to those of another.
2088 #[stable(feature = "iter_order", since = "1.5.0")]
2089 fn le<I>(mut self, other: I) -> bool where
2091 Self::Item: PartialOrd<I::Item>,
2094 let mut other = other.into_iter();
2097 match (self.next(), other.next()) {
2098 (None, None) => return true,
2099 (None, _ ) => return true,
2100 (_ , None) => return false,
2101 (Some(x), Some(y)) => {
2102 match x.partial_cmp(&y) {
2103 Some(Ordering::Less) => return true,
2104 Some(Ordering::Equal) => {}
2105 Some(Ordering::Greater) => return false,
2106 None => return false,
2113 /// Determines if the elements of this `Iterator` are lexicographically
2114 /// greater than those of another.
2115 #[stable(feature = "iter_order", since = "1.5.0")]
2116 fn gt<I>(mut self, other: I) -> bool where
2118 Self::Item: PartialOrd<I::Item>,
2121 let mut other = other.into_iter();
2124 match (self.next(), other.next()) {
2125 (None, None) => return false,
2126 (None, _ ) => return false,
2127 (_ , None) => return true,
2128 (Some(x), Some(y)) => {
2129 match x.partial_cmp(&y) {
2130 Some(Ordering::Less) => return false,
2131 Some(Ordering::Equal) => {}
2132 Some(Ordering::Greater) => return true,
2133 None => return false,
2140 /// Determines if the elements of this `Iterator` are lexicographically
2141 /// greater than or equal to those of another.
2142 #[stable(feature = "iter_order", since = "1.5.0")]
2143 fn ge<I>(mut self, other: I) -> bool where
2145 Self::Item: PartialOrd<I::Item>,
2148 let mut other = other.into_iter();
2151 match (self.next(), other.next()) {
2152 (None, None) => return true,
2153 (None, _ ) => return false,
2154 (_ , None) => return true,
2155 (Some(x), Some(y)) => {
2156 match x.partial_cmp(&y) {
2157 Some(Ordering::Less) => return false,
2158 Some(Ordering::Equal) => {}
2159 Some(Ordering::Greater) => return true,
2160 None => return false,
2168 /// Select an element from an iterator based on the given "projection"
2169 /// and "comparison" function.
2171 /// This is an idiosyncratic helper to try to factor out the
2172 /// commonalities of {max,min}{,_by}. In particular, this avoids
2173 /// having to implement optimizations several times.
2175 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2177 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2179 FProj: FnMut(&I::Item) -> B,
2180 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2182 // start with the first element as our selection. This avoids
2183 // having to use `Option`s inside the loop, translating to a
2184 // sizeable performance gain (6x in one case).
2185 it.next().map(|mut sel| {
2186 let mut sel_p = f_proj(&sel);
2189 let x_p = f_proj(&x);
2190 if f_cmp(&sel_p, &sel, &x_p, &x) {
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2201 type Item = I::Item;
2202 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2203 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2204 fn nth(&mut self, n: usize) -> Option<Self::Item> {