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.
15 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, Fuse};
16 use super::{Flatten, FlatMap, flatten_compat};
17 use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
18 use super::{Zip, Sum, Product};
19 use super::{ChainState, FromIterator, ZipImpl};
21 fn _assert_is_object_safe(_: &dyn Iterator<Item=()>) {}
23 /// An interface for dealing with iterators.
25 /// This is the main iterator trait. For more about the concept of iterators
26 /// generally, please see the [module-level documentation]. In particular, you
27 /// may want to know how to [implement `Iterator`][impl].
29 /// [module-level documentation]: index.html
30 /// [impl]: index.html#implementing-iterator
31 #[stable(feature = "rust1", since = "1.0.0")]
32 #[rustc_on_unimplemented(
34 _Self="[std::ops::Range<Idx>; 1]",
35 label="if you meant to iterate between two values, remove the square brackets",
36 note="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
37 without the brackets: `start..end`"
40 _Self="[std::ops::RangeFrom<Idx>; 1]",
41 label="if you meant to iterate from a value onwards, remove the square brackets",
42 note="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
43 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
44 unbounded iterator will run forever unless you `break` or `return` from within the \
48 _Self="[std::ops::RangeTo<Idx>; 1]",
49 label="if you meant to iterate until a value, remove the square brackets and add a \
51 note="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
52 `Range` without the brackets: `0..end`"
55 _Self="[std::ops::RangeInclusive<Idx>; 1]",
56 label="if you meant to iterate between two values, remove the square brackets",
57 note="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
58 `RangeInclusive` without the brackets: `start..=end`"
61 _Self="[std::ops::RangeToInclusive<Idx>; 1]",
62 label="if you meant to iterate until a value (including it), remove the square brackets \
63 and add a starting value",
64 note="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
65 bounded `RangeInclusive` without the brackets: `0..=end`"
68 _Self="std::ops::RangeTo<Idx>",
69 label="if you meant to iterate until a value, add a starting value",
70 note="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
71 bounded `Range`: `0..end`"
74 _Self="std::ops::RangeToInclusive<Idx>",
75 label="if you meant to iterate until a value (including it), add a starting value",
76 note="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
77 to have a bounded `RangeInclusive`: `0..=end`"
81 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
84 _Self="std::string::String",
85 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
89 label="borrow the array with `&` or call `.iter()` on it to iterate over it",
90 note="arrays are not an iterators, but slices like the following are: `&[1, 2, 3]`"
94 note="if you want to iterate between `start` until a value `end`, use the exclusive range \
95 syntax `start..end` or the inclusive range syntax `start..=end`"
97 label="`{Self}` is not an iterator",
98 message="`{Self}` is not an iterator"
102 /// The type of the elements being iterated over.
103 #[stable(feature = "rust1", since = "1.0.0")]
106 /// Advances the iterator and returns the next value.
108 /// Returns [`None`] when iteration is finished. Individual iterator
109 /// implementations may choose to resume iteration, and so calling `next()`
110 /// again may or may not eventually start returning [`Some(Item)`] again at some
113 /// [`None`]: ../../std/option/enum.Option.html#variant.None
114 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
121 /// let a = [1, 2, 3];
123 /// let mut iter = a.iter();
125 /// // A call to next() returns the next value...
126 /// assert_eq!(Some(&1), iter.next());
127 /// assert_eq!(Some(&2), iter.next());
128 /// assert_eq!(Some(&3), iter.next());
130 /// // ... and then None once it's over.
131 /// assert_eq!(None, iter.next());
133 /// // More calls may or may not return None. Here, they always will.
134 /// assert_eq!(None, iter.next());
135 /// assert_eq!(None, iter.next());
137 #[stable(feature = "rust1", since = "1.0.0")]
138 fn next(&mut self) -> Option<Self::Item>;
140 /// Returns the bounds on the remaining length of the iterator.
142 /// Specifically, `size_hint()` returns a tuple where the first element
143 /// is the lower bound, and the second element is the upper bound.
145 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
146 /// A [`None`] here means that either there is no known upper bound, or the
147 /// upper bound is larger than [`usize`].
149 /// # Implementation notes
151 /// It is not enforced that an iterator implementation yields the declared
152 /// number of elements. A buggy iterator may yield less than the lower bound
153 /// or more than the upper bound of elements.
155 /// `size_hint()` is primarily intended to be used for optimizations such as
156 /// reserving space for the elements of the iterator, but must not be
157 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
158 /// implementation of `size_hint()` should not lead to memory safety
161 /// That said, the implementation should provide a correct estimation,
162 /// because otherwise it would be a violation of the trait's protocol.
164 /// The default implementation returns `(0, None)` which is correct for any
167 /// [`usize`]: ../../std/primitive.usize.html
168 /// [`Option`]: ../../std/option/enum.Option.html
169 /// [`None`]: ../../std/option/enum.Option.html#variant.None
176 /// let a = [1, 2, 3];
177 /// let iter = a.iter();
179 /// assert_eq!((3, Some(3)), iter.size_hint());
182 /// A more complex example:
185 /// // The even numbers from zero to ten.
186 /// let iter = (0..10).filter(|x| x % 2 == 0);
188 /// // We might iterate from zero to ten times. Knowing that it's five
189 /// // exactly wouldn't be possible without executing filter().
190 /// assert_eq!((0, Some(10)), iter.size_hint());
192 /// // Let's add five more numbers with chain()
193 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
195 /// // now both bounds are increased by five
196 /// assert_eq!((5, Some(15)), iter.size_hint());
199 /// Returning `None` for an upper bound:
202 /// // an infinite iterator has no upper bound
203 /// // and the maximum possible lower bound
206 /// assert_eq!((usize::max_value(), None), iter.size_hint());
209 #[stable(feature = "rust1", since = "1.0.0")]
210 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
212 /// Consumes the iterator, counting the number of iterations and returning it.
214 /// This method will evaluate the iterator until its [`next`] returns
215 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
216 /// times it called [`next`].
218 /// [`next`]: #tymethod.next
219 /// [`None`]: ../../std/option/enum.Option.html#variant.None
221 /// # Overflow Behavior
223 /// The method does no guarding against overflows, so counting elements of
224 /// an iterator with more than [`usize::MAX`] elements either produces the
225 /// wrong result or panics. If debug assertions are enabled, a panic is
230 /// This function might panic if the iterator has more than [`usize::MAX`]
233 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
240 /// let a = [1, 2, 3];
241 /// assert_eq!(a.iter().count(), 3);
243 /// let a = [1, 2, 3, 4, 5];
244 /// assert_eq!(a.iter().count(), 5);
247 #[rustc_inherit_overflow_checks]
248 #[stable(feature = "rust1", since = "1.0.0")]
249 fn count(self) -> usize where Self: Sized {
251 self.fold(0, |cnt, _| cnt + 1)
254 /// Consumes the iterator, returning the last element.
256 /// This method will evaluate the iterator until it returns [`None`]. While
257 /// doing so, it keeps track of the current element. After [`None`] is
258 /// returned, `last()` will then return the last element it saw.
260 /// [`None`]: ../../std/option/enum.Option.html#variant.None
267 /// let a = [1, 2, 3];
268 /// assert_eq!(a.iter().last(), Some(&3));
270 /// let a = [1, 2, 3, 4, 5];
271 /// assert_eq!(a.iter().last(), Some(&5));
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn last(self) -> Option<Self::Item> where Self: Sized {
277 for x in self { last = Some(x); }
281 /// Returns the `n`th element of the iterator.
283 /// Like most indexing operations, the count starts from zero, so `nth(0)`
284 /// returns the first value, `nth(1)` the second, and so on.
286 /// Note that all preceding elements, as well as the returned element, will be
287 /// consumed from the iterator. That means that the preceding elements will be
288 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
289 /// will return different elements.
291 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
294 /// [`None`]: ../../std/option/enum.Option.html#variant.None
301 /// let a = [1, 2, 3];
302 /// assert_eq!(a.iter().nth(1), Some(&2));
305 /// Calling `nth()` multiple times doesn't rewind the iterator:
308 /// let a = [1, 2, 3];
310 /// let mut iter = a.iter();
312 /// assert_eq!(iter.nth(1), Some(&2));
313 /// assert_eq!(iter.nth(1), None);
316 /// Returning `None` if there are less than `n + 1` elements:
319 /// let a = [1, 2, 3];
320 /// assert_eq!(a.iter().nth(10), None);
323 #[stable(feature = "rust1", since = "1.0.0")]
324 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
326 if n == 0 { return Some(x) }
332 /// Creates an iterator starting at the same point, but stepping by
333 /// the given amount at each iteration.
335 /// Note 1: The first element of the iterator will always be returned,
336 /// regardless of the step given.
338 /// Note 2: The time at which ignored elements are pulled is not fixed.
339 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
340 /// but is also free to behave like the sequence
341 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
342 /// Which way is used may change for some iterators for performance reasons.
343 /// The second way will advance the iterator earlier and may consume more items.
345 /// `advance_n_and_return_first` is the equivalent of:
347 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
351 /// let next = iter.next();
352 /// if total_step > 1 {
353 /// iter.nth(total_step-2);
361 /// The method will panic if the given step is `0`.
368 /// let a = [0, 1, 2, 3, 4, 5];
369 /// let mut iter = a.into_iter().step_by(2);
371 /// assert_eq!(iter.next(), Some(&0));
372 /// assert_eq!(iter.next(), Some(&2));
373 /// assert_eq!(iter.next(), Some(&4));
374 /// assert_eq!(iter.next(), None);
377 #[stable(feature = "iterator_step_by", since = "1.28.0")]
378 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
380 StepBy{iter: self, step: step - 1, first_take: true}
383 /// Takes two iterators and creates a new iterator over both in sequence.
385 /// `chain()` will return a new iterator which will first iterate over
386 /// values from the first iterator and then over values from the second
389 /// In other words, it links two iterators together, in a chain. 🔗
396 /// let a1 = [1, 2, 3];
397 /// let a2 = [4, 5, 6];
399 /// let mut iter = a1.iter().chain(a2.iter());
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);
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:
415 /// [`IntoIterator`]: trait.IntoIterator.html
416 /// [`Iterator`]: trait.Iterator.html
419 /// let s1 = &[1, 2, 3];
420 /// let s2 = &[4, 5, 6];
422 /// let mut iter = s1.iter().chain(s2);
424 /// assert_eq!(iter.next(), Some(&1));
425 /// assert_eq!(iter.next(), Some(&2));
426 /// assert_eq!(iter.next(), Some(&3));
427 /// assert_eq!(iter.next(), Some(&4));
428 /// assert_eq!(iter.next(), Some(&5));
429 /// assert_eq!(iter.next(), Some(&6));
430 /// assert_eq!(iter.next(), None);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
435 Self: Sized, U: IntoIterator<Item=Self::Item>,
437 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
440 /// 'Zips up' two iterators into a single iterator of pairs.
442 /// `zip()` returns a new iterator that will iterate over two other
443 /// iterators, returning a tuple where the first element comes from the
444 /// first iterator, and the second element comes from the second iterator.
446 /// In other words, it zips two iterators together, into a single one.
448 /// If either iterator returns [`None`], [`next`] from the zipped iterator
449 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
450 /// short-circuit and `next` will not be called on the second iterator.
457 /// let a1 = [1, 2, 3];
458 /// let a2 = [4, 5, 6];
460 /// let mut iter = a1.iter().zip(a2.iter());
462 /// assert_eq!(iter.next(), Some((&1, &4)));
463 /// assert_eq!(iter.next(), Some((&2, &5)));
464 /// assert_eq!(iter.next(), Some((&3, &6)));
465 /// assert_eq!(iter.next(), None);
468 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
469 /// anything that can be converted into an [`Iterator`], not just an
470 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
471 /// [`IntoIterator`], and so can be passed to `zip()` directly:
473 /// [`IntoIterator`]: trait.IntoIterator.html
474 /// [`Iterator`]: trait.Iterator.html
477 /// let s1 = &[1, 2, 3];
478 /// let s2 = &[4, 5, 6];
480 /// let mut iter = s1.iter().zip(s2);
482 /// assert_eq!(iter.next(), Some((&1, &4)));
483 /// assert_eq!(iter.next(), Some((&2, &5)));
484 /// assert_eq!(iter.next(), Some((&3, &6)));
485 /// assert_eq!(iter.next(), None);
488 /// `zip()` is often used to zip an infinite iterator to a finite one.
489 /// This works because the finite iterator will eventually return [`None`],
490 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
493 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
495 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
497 /// assert_eq!((0, 'f'), enumerate[0]);
498 /// assert_eq!((0, 'f'), zipper[0]);
500 /// assert_eq!((1, 'o'), enumerate[1]);
501 /// assert_eq!((1, 'o'), zipper[1]);
503 /// assert_eq!((2, 'o'), enumerate[2]);
504 /// assert_eq!((2, 'o'), zipper[2]);
507 /// [`enumerate`]: trait.Iterator.html#method.enumerate
508 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
509 /// [`None`]: ../../std/option/enum.Option.html#variant.None
511 #[stable(feature = "rust1", since = "1.0.0")]
512 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
513 Self: Sized, U: IntoIterator
515 Zip::new(self, other.into_iter())
518 /// Takes a closure and creates an iterator which calls that closure on each
521 /// `map()` transforms one iterator into another, by means of its argument:
522 /// something that implements [`FnMut`]. It produces a new iterator which
523 /// calls this closure on each element of the original iterator.
525 /// If you are good at thinking in types, you can think of `map()` like this:
526 /// If you have an iterator that gives you elements of some type `A`, and
527 /// you want an iterator of some other type `B`, you can use `map()`,
528 /// passing a closure that takes an `A` and returns a `B`.
530 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
531 /// lazy, it is best used when you're already working with other iterators.
532 /// If you're doing some sort of looping for a side effect, it's considered
533 /// more idiomatic to use [`for`] than `map()`.
535 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
536 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
543 /// let a = [1, 2, 3];
545 /// let mut iter = a.into_iter().map(|x| 2 * x);
547 /// assert_eq!(iter.next(), Some(2));
548 /// assert_eq!(iter.next(), Some(4));
549 /// assert_eq!(iter.next(), Some(6));
550 /// assert_eq!(iter.next(), None);
553 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
556 /// # #![allow(unused_must_use)]
557 /// // don't do this:
558 /// (0..5).map(|x| println!("{}", x));
560 /// // it won't even execute, as it is lazy. Rust will warn you about this.
562 /// // Instead, use for:
564 /// println!("{}", x);
568 #[stable(feature = "rust1", since = "1.0.0")]
569 fn map<B, F>(self, f: F) -> Map<Self, F> where
570 Self: Sized, F: FnMut(Self::Item) -> B,
572 Map { iter: self, f }
575 /// Calls a closure on each element of an iterator.
577 /// This is equivalent to using a [`for`] loop on the iterator, although
578 /// `break` and `continue` are not possible from a closure. It's generally
579 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
580 /// when processing items at the end of longer iterator chains. In some
581 /// cases `for_each` may also be faster than a loop, because it will use
582 /// internal iteration on adaptors like `Chain`.
584 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
591 /// use std::sync::mpsc::channel;
593 /// let (tx, rx) = channel();
594 /// (0..5).map(|x| x * 2 + 1)
595 /// .for_each(move |x| tx.send(x).unwrap());
597 /// let v: Vec<_> = rx.iter().collect();
598 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
601 /// For such a small example, a `for` loop may be cleaner, but `for_each`
602 /// might be preferable to keep a functional style with longer iterators:
605 /// (0..5).flat_map(|x| x * 100 .. x * 110)
607 /// .filter(|&(i, x)| (i + x) % 3 == 0)
608 /// .for_each(|(i, x)| println!("{}:{}", i, x));
611 #[stable(feature = "iterator_for_each", since = "1.21.0")]
612 fn for_each<F>(self, mut f: F) where
613 Self: Sized, F: FnMut(Self::Item),
615 self.fold((), move |(), item| f(item));
618 /// Creates an iterator which uses a closure to determine if an element
619 /// should be yielded.
621 /// The closure must return `true` or `false`. `filter()` creates an
622 /// iterator which calls this closure on each element. If the closure
623 /// returns `true`, then the element is returned. If the closure returns
624 /// `false`, it will try again, and call the closure on the next element,
625 /// seeing if it passes the test.
632 /// let a = [0i32, 1, 2];
634 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
636 /// assert_eq!(iter.next(), Some(&1));
637 /// assert_eq!(iter.next(), Some(&2));
638 /// assert_eq!(iter.next(), None);
641 /// Because the closure passed to `filter()` takes a reference, and many
642 /// iterators iterate over references, this leads to a possibly confusing
643 /// situation, where the type of the closure is a double reference:
646 /// let a = [0, 1, 2];
648 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
650 /// assert_eq!(iter.next(), Some(&2));
651 /// assert_eq!(iter.next(), None);
654 /// It's common to instead use destructuring on the argument to strip away
658 /// let a = [0, 1, 2];
660 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
662 /// assert_eq!(iter.next(), Some(&2));
663 /// assert_eq!(iter.next(), None);
669 /// let a = [0, 1, 2];
671 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
673 /// assert_eq!(iter.next(), Some(&2));
674 /// assert_eq!(iter.next(), None);
679 #[stable(feature = "rust1", since = "1.0.0")]
680 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
681 Self: Sized, P: FnMut(&Self::Item) -> bool,
683 Filter {iter: self, predicate }
686 /// Creates an iterator that both filters and maps.
688 /// The closure must return an [`Option<T>`]. `filter_map` creates an
689 /// iterator which calls this closure on each element. If the closure
690 /// returns [`Some(element)`][`Some`], then that element is returned. If the
691 /// closure returns [`None`], it will try again, and call the closure on the
692 /// next element, seeing if it will return [`Some`].
694 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
697 /// [`filter`]: #method.filter
698 /// [`map`]: #method.map
700 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
702 /// In other words, it removes the [`Option<T>`] layer automatically. If your
703 /// mapping is already returning an [`Option<T>`] and you want to skip over
704 /// [`None`]s, then `filter_map` is much, much nicer to use.
711 /// let a = ["1", "lol", "3", "NaN", "5"];
713 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
715 /// assert_eq!(iter.next(), Some(1));
716 /// assert_eq!(iter.next(), Some(3));
717 /// assert_eq!(iter.next(), Some(5));
718 /// assert_eq!(iter.next(), None);
721 /// Here's the same example, but with [`filter`] and [`map`]:
724 /// let a = ["1", "lol", "3", "NaN", "5"];
725 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
726 /// assert_eq!(iter.next(), Some(1));
727 /// assert_eq!(iter.next(), Some(3));
728 /// assert_eq!(iter.next(), Some(5));
729 /// assert_eq!(iter.next(), None);
732 /// [`Option<T>`]: ../../std/option/enum.Option.html
733 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
734 /// [`None`]: ../../std/option/enum.Option.html#variant.None
736 #[stable(feature = "rust1", since = "1.0.0")]
737 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
738 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
740 FilterMap { iter: self, f }
743 /// Creates an iterator which gives the current iteration count as well as
746 /// The iterator returned yields pairs `(i, val)`, where `i` is the
747 /// current index of iteration and `val` is the value returned by the
750 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
751 /// different sized integer, the [`zip`] function provides similar
754 /// # Overflow Behavior
756 /// The method does no guarding against overflows, so enumerating more than
757 /// [`usize::MAX`] elements either produces the wrong result or panics. If
758 /// debug assertions are enabled, a panic is guaranteed.
762 /// The returned iterator might panic if the to-be-returned index would
763 /// overflow a [`usize`].
765 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
766 /// [`usize`]: ../../std/primitive.usize.html
767 /// [`zip`]: #method.zip
772 /// let a = ['a', 'b', 'c'];
774 /// let mut iter = a.iter().enumerate();
776 /// assert_eq!(iter.next(), Some((0, &'a')));
777 /// assert_eq!(iter.next(), Some((1, &'b')));
778 /// assert_eq!(iter.next(), Some((2, &'c')));
779 /// assert_eq!(iter.next(), None);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
784 Enumerate { iter: self, count: 0 }
787 /// Creates an iterator which can use `peek` to look at the next element of
788 /// the iterator without consuming it.
790 /// Adds a [`peek`] method to an iterator. See its documentation for
791 /// more information.
793 /// Note that the underlying iterator is still advanced when [`peek`] is
794 /// called for the first time: In order to retrieve the next element,
795 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
796 /// anything other than fetching the next value) of the [`next`] method
799 /// [`peek`]: struct.Peekable.html#method.peek
800 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
807 /// let xs = [1, 2, 3];
809 /// let mut iter = xs.iter().peekable();
811 /// // peek() lets us see into the future
812 /// assert_eq!(iter.peek(), Some(&&1));
813 /// assert_eq!(iter.next(), Some(&1));
815 /// assert_eq!(iter.next(), Some(&2));
817 /// // we can peek() multiple times, the iterator won't advance
818 /// assert_eq!(iter.peek(), Some(&&3));
819 /// assert_eq!(iter.peek(), Some(&&3));
821 /// assert_eq!(iter.next(), Some(&3));
823 /// // after the iterator is finished, so is peek()
824 /// assert_eq!(iter.peek(), None);
825 /// assert_eq!(iter.next(), None);
828 #[stable(feature = "rust1", since = "1.0.0")]
829 fn peekable(self) -> Peekable<Self> where Self: Sized {
830 Peekable{iter: self, peeked: None}
833 /// Creates an iterator that [`skip`]s elements based on a predicate.
835 /// [`skip`]: #method.skip
837 /// `skip_while()` takes a closure as an argument. It will call this
838 /// closure on each element of the iterator, and ignore elements
839 /// until it returns `false`.
841 /// After `false` is returned, `skip_while()`'s job is over, and the
842 /// rest of the elements are yielded.
849 /// let a = [-1i32, 0, 1];
851 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
853 /// assert_eq!(iter.next(), Some(&0));
854 /// assert_eq!(iter.next(), Some(&1));
855 /// assert_eq!(iter.next(), None);
858 /// Because the closure passed to `skip_while()` takes a reference, and many
859 /// iterators iterate over references, this leads to a possibly confusing
860 /// situation, where the type of the closure is a double reference:
863 /// let a = [-1, 0, 1];
865 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
867 /// assert_eq!(iter.next(), Some(&0));
868 /// assert_eq!(iter.next(), Some(&1));
869 /// assert_eq!(iter.next(), None);
872 /// Stopping after an initial `false`:
875 /// let a = [-1, 0, 1, -2];
877 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
879 /// assert_eq!(iter.next(), Some(&0));
880 /// assert_eq!(iter.next(), Some(&1));
882 /// // while this would have been false, since we already got a false,
883 /// // skip_while() isn't used any more
884 /// assert_eq!(iter.next(), Some(&-2));
886 /// assert_eq!(iter.next(), None);
889 #[stable(feature = "rust1", since = "1.0.0")]
890 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
891 Self: Sized, P: FnMut(&Self::Item) -> bool,
893 SkipWhile { iter: self, flag: false, predicate }
896 /// Creates an iterator that yields elements based on a predicate.
898 /// `take_while()` takes a closure as an argument. It will call this
899 /// closure on each element of the iterator, and yield elements
900 /// while it returns `true`.
902 /// After `false` is returned, `take_while()`'s job is over, and the
903 /// rest of the elements are ignored.
910 /// let a = [-1i32, 0, 1];
912 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
914 /// assert_eq!(iter.next(), Some(&-1));
915 /// assert_eq!(iter.next(), None);
918 /// Because the closure passed to `take_while()` takes a reference, and many
919 /// iterators iterate over references, this leads to a possibly confusing
920 /// situation, where the type of the closure is a double reference:
923 /// let a = [-1, 0, 1];
925 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
927 /// assert_eq!(iter.next(), Some(&-1));
928 /// assert_eq!(iter.next(), None);
931 /// Stopping after an initial `false`:
934 /// let a = [-1, 0, 1, -2];
936 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
938 /// assert_eq!(iter.next(), Some(&-1));
940 /// // We have more elements that are less than zero, but since we already
941 /// // got a false, take_while() isn't used any more
942 /// assert_eq!(iter.next(), None);
945 /// Because `take_while()` needs to look at the value in order to see if it
946 /// should be included or not, consuming iterators will see that it is
950 /// let a = [1, 2, 3, 4];
951 /// let mut iter = a.into_iter();
953 /// let result: Vec<i32> = iter.by_ref()
954 /// .take_while(|n| **n != 3)
958 /// assert_eq!(result, &[1, 2]);
960 /// let result: Vec<i32> = iter.cloned().collect();
962 /// assert_eq!(result, &[4]);
965 /// The `3` is no longer there, because it was consumed in order to see if
966 /// the iteration should stop, but wasn't placed back into the iterator or
967 /// some similar thing.
969 #[stable(feature = "rust1", since = "1.0.0")]
970 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
971 Self: Sized, P: FnMut(&Self::Item) -> bool,
973 TakeWhile { iter: self, flag: false, predicate }
976 /// Creates an iterator that skips the first `n` elements.
978 /// After they have been consumed, the rest of the elements are yielded.
985 /// let a = [1, 2, 3];
987 /// let mut iter = a.iter().skip(2);
989 /// assert_eq!(iter.next(), Some(&3));
990 /// assert_eq!(iter.next(), None);
993 #[stable(feature = "rust1", since = "1.0.0")]
994 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
995 Skip { iter: self, n }
998 /// Creates an iterator that yields its first `n` elements.
1005 /// let a = [1, 2, 3];
1007 /// let mut iter = a.iter().take(2);
1009 /// assert_eq!(iter.next(), Some(&1));
1010 /// assert_eq!(iter.next(), Some(&2));
1011 /// assert_eq!(iter.next(), None);
1014 /// `take()` is often used with an infinite iterator, to make it finite:
1017 /// let mut iter = (0..).take(3);
1019 /// assert_eq!(iter.next(), Some(0));
1020 /// assert_eq!(iter.next(), Some(1));
1021 /// assert_eq!(iter.next(), Some(2));
1022 /// assert_eq!(iter.next(), None);
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1027 Take { iter: self, n }
1030 /// An iterator adaptor similar to [`fold`] that holds internal state and
1031 /// produces a new iterator.
1033 /// [`fold`]: #method.fold
1035 /// `scan()` takes two arguments: an initial value which seeds the internal
1036 /// state, and a closure with two arguments, the first being a mutable
1037 /// reference to the internal state and the second an iterator element.
1038 /// The closure can assign to the internal state to share state between
1041 /// On iteration, the closure will be applied to each element of the
1042 /// iterator and the return value from the closure, an [`Option`], is
1043 /// yielded by the iterator.
1045 /// [`Option`]: ../../std/option/enum.Option.html
1052 /// let a = [1, 2, 3];
1054 /// let mut iter = a.iter().scan(1, |state, &x| {
1055 /// // each iteration, we'll multiply the state by the element
1056 /// *state = *state * x;
1058 /// // then, we'll yield the negation of the state
1062 /// assert_eq!(iter.next(), Some(-1));
1063 /// assert_eq!(iter.next(), Some(-2));
1064 /// assert_eq!(iter.next(), Some(-6));
1065 /// assert_eq!(iter.next(), None);
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1070 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1072 Scan { iter: self, f, state: initial_state }
1075 /// Creates an iterator that works like map, but flattens nested structure.
1077 /// The [`map`] adapter is very useful, but only when the closure
1078 /// argument produces values. If it produces an iterator instead, there's
1079 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1082 /// You can think of `flat_map(f)` as the semantic equivalent
1083 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1085 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1086 /// one item for each element, and `flat_map()`'s closure returns an
1087 /// iterator for each element.
1089 /// [`map`]: #method.map
1090 /// [`flatten`]: #method.flatten
1097 /// let words = ["alpha", "beta", "gamma"];
1099 /// // chars() returns an iterator
1100 /// let merged: String = words.iter()
1101 /// .flat_map(|s| s.chars())
1103 /// assert_eq!(merged, "alphabetagamma");
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1108 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1110 FlatMap { inner: flatten_compat(self.map(f)) }
1113 /// Creates an iterator that flattens nested structure.
1115 /// This is useful when you have an iterator of iterators or an iterator of
1116 /// things that can be turned into iterators and you want to remove one
1117 /// level of indirection.
1124 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1125 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1126 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1129 /// Mapping and then flattening:
1132 /// let words = ["alpha", "beta", "gamma"];
1134 /// // chars() returns an iterator
1135 /// let merged: String = words.iter()
1136 /// .map(|s| s.chars())
1139 /// assert_eq!(merged, "alphabetagamma");
1142 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1143 /// in this case since it conveys intent more clearly:
1146 /// let words = ["alpha", "beta", "gamma"];
1148 /// // chars() returns an iterator
1149 /// let merged: String = words.iter()
1150 /// .flat_map(|s| s.chars())
1152 /// assert_eq!(merged, "alphabetagamma");
1155 /// Flattening once only removes one level of nesting:
1158 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1160 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1161 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1163 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1164 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1167 /// Here we see that `flatten()` does not perform a "deep" flatten.
1168 /// Instead, only one level of nesting is removed. That is, if you
1169 /// `flatten()` a three-dimensional array the result will be
1170 /// two-dimensional and not one-dimensional. To get a one-dimensional
1171 /// structure, you have to `flatten()` again.
1173 /// [`flat_map()`]: #method.flat_map
1175 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1176 fn flatten(self) -> Flatten<Self>
1177 where Self: Sized, Self::Item: IntoIterator {
1178 Flatten { inner: flatten_compat(self) }
1181 /// Creates an iterator which ends after the first [`None`].
1183 /// After an iterator returns [`None`], future calls may or may not yield
1184 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1185 /// [`None`] is given, it will always return [`None`] forever.
1187 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1188 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1195 /// // an iterator which alternates between Some and None
1196 /// struct Alternate {
1200 /// impl Iterator for Alternate {
1201 /// type Item = i32;
1203 /// fn next(&mut self) -> Option<i32> {
1204 /// let val = self.state;
1205 /// self.state = self.state + 1;
1207 /// // if it's even, Some(i32), else None
1208 /// if val % 2 == 0 {
1216 /// let mut iter = Alternate { state: 0 };
1218 /// // we can see our iterator going back and forth
1219 /// assert_eq!(iter.next(), Some(0));
1220 /// assert_eq!(iter.next(), None);
1221 /// assert_eq!(iter.next(), Some(2));
1222 /// assert_eq!(iter.next(), None);
1224 /// // however, once we fuse it...
1225 /// let mut iter = iter.fuse();
1227 /// assert_eq!(iter.next(), Some(4));
1228 /// assert_eq!(iter.next(), None);
1230 /// // it will always return None after the first time.
1231 /// assert_eq!(iter.next(), None);
1232 /// assert_eq!(iter.next(), None);
1233 /// assert_eq!(iter.next(), None);
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 fn fuse(self) -> Fuse<Self> where Self: Sized {
1238 Fuse{iter: self, done: false}
1241 /// Do something with each element of an iterator, passing the value on.
1243 /// When using iterators, you'll often chain several of them together.
1244 /// While working on such code, you might want to check out what's
1245 /// happening at various parts in the pipeline. To do that, insert
1246 /// a call to `inspect()`.
1248 /// It's more common for `inspect()` to be used as a debugging tool than to
1249 /// exist in your final code, but applications may find it useful in certain
1250 /// situations when errors need to be logged before being discarded.
1257 /// let a = [1, 4, 2, 3];
1259 /// // this iterator sequence is complex.
1260 /// let sum = a.iter()
1262 /// .filter(|x| x % 2 == 0)
1263 /// .fold(0, |sum, i| sum + i);
1265 /// println!("{}", sum);
1267 /// // let's add some inspect() calls to investigate what's happening
1268 /// let sum = a.iter()
1270 /// .inspect(|x| println!("about to filter: {}", x))
1271 /// .filter(|x| x % 2 == 0)
1272 /// .inspect(|x| println!("made it through filter: {}", x))
1273 /// .fold(0, |sum, i| sum + i);
1275 /// println!("{}", sum);
1278 /// This will print:
1282 /// about to filter: 1
1283 /// about to filter: 4
1284 /// made it through filter: 4
1285 /// about to filter: 2
1286 /// made it through filter: 2
1287 /// about to filter: 3
1291 /// Logging errors before discarding them:
1294 /// let lines = ["1", "2", "a"];
1296 /// let sum: i32 = lines
1298 /// .map(|line| line.parse::<i32>())
1299 /// .inspect(|num| {
1300 /// if let Err(ref e) = *num {
1301 /// println!("Parsing error: {}", e);
1304 /// .filter_map(Result::ok)
1307 /// println!("Sum: {}", sum);
1310 /// This will print:
1313 /// Parsing error: invalid digit found in string
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1319 Self: Sized, F: FnMut(&Self::Item),
1321 Inspect { iter: self, f }
1324 /// Borrows an iterator, rather than consuming it.
1326 /// This is useful to allow applying iterator adaptors while still
1327 /// retaining ownership of the original iterator.
1334 /// let a = [1, 2, 3];
1336 /// let iter = a.into_iter();
1338 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1340 /// assert_eq!(sum, 6);
1342 /// // if we try to use iter again, it won't work. The following line
1343 /// // gives "error: use of moved value: `iter`
1344 /// // assert_eq!(iter.next(), None);
1346 /// // let's try that again
1347 /// let a = [1, 2, 3];
1349 /// let mut iter = a.into_iter();
1351 /// // instead, we add in a .by_ref()
1352 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1354 /// assert_eq!(sum, 3);
1356 /// // now this is just fine:
1357 /// assert_eq!(iter.next(), Some(&3));
1358 /// assert_eq!(iter.next(), None);
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1363 /// Transforms an iterator into a collection.
1365 /// `collect()` can take anything iterable, and turn it into a relevant
1366 /// collection. This is one of the more powerful methods in the standard
1367 /// library, used in a variety of contexts.
1369 /// The most basic pattern in which `collect()` is used is to turn one
1370 /// collection into another. You take a collection, call [`iter`] on it,
1371 /// do a bunch of transformations, and then `collect()` at the end.
1373 /// One of the keys to `collect()`'s power is that many things you might
1374 /// not think of as 'collections' actually are. For example, a [`String`]
1375 /// is a collection of [`char`]s. And a collection of
1376 /// [`Result<T, E>`][`Result`] can be thought of as single
1377 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1379 /// Because `collect()` is so general, it can cause problems with type
1380 /// inference. As such, `collect()` is one of the few times you'll see
1381 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1382 /// helps the inference algorithm understand specifically which collection
1383 /// you're trying to collect into.
1390 /// let a = [1, 2, 3];
1392 /// let doubled: Vec<i32> = a.iter()
1393 /// .map(|&x| x * 2)
1396 /// assert_eq!(vec![2, 4, 6], doubled);
1399 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1400 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1402 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1405 /// use std::collections::VecDeque;
1407 /// let a = [1, 2, 3];
1409 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1411 /// assert_eq!(2, doubled[0]);
1412 /// assert_eq!(4, doubled[1]);
1413 /// assert_eq!(6, doubled[2]);
1416 /// Using the 'turbofish' instead of annotating `doubled`:
1419 /// let a = [1, 2, 3];
1421 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1423 /// assert_eq!(vec![2, 4, 6], doubled);
1426 /// Because `collect()` only cares about what you're collecting into, you can
1427 /// still use a partial type hint, `_`, with the turbofish:
1430 /// let a = [1, 2, 3];
1432 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1434 /// assert_eq!(vec![2, 4, 6], doubled);
1437 /// Using `collect()` to make a [`String`]:
1440 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1442 /// let hello: String = chars.iter()
1443 /// .map(|&x| x as u8)
1444 /// .map(|x| (x + 1) as char)
1447 /// assert_eq!("hello", hello);
1450 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1451 /// see if any of them failed:
1454 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1456 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1458 /// // gives us the first error
1459 /// assert_eq!(Err("nope"), result);
1461 /// let results = [Ok(1), Ok(3)];
1463 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1465 /// // gives us the list of answers
1466 /// assert_eq!(Ok(vec![1, 3]), result);
1469 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1470 /// [`String`]: ../../std/string/struct.String.html
1471 /// [`char`]: ../../std/primitive.char.html
1472 /// [`Result`]: ../../std/result/enum.Result.html
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1476 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1477 FromIterator::from_iter(self)
1480 /// Consumes an iterator, creating two collections from it.
1482 /// The predicate passed to `partition()` can return `true`, or `false`.
1483 /// `partition()` returns a pair, all of the elements for which it returned
1484 /// `true`, and all of the elements for which it returned `false`.
1491 /// let a = [1, 2, 3];
1493 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1495 /// .partition(|&n| n % 2 == 0);
1497 /// assert_eq!(even, vec![2]);
1498 /// assert_eq!(odd, vec![1, 3]);
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 fn partition<B, F>(self, mut f: F) -> (B, B) where
1503 B: Default + Extend<Self::Item>,
1504 F: FnMut(&Self::Item) -> bool
1506 let mut left: B = Default::default();
1507 let mut right: B = Default::default();
1511 left.extend(Some(x))
1513 right.extend(Some(x))
1520 /// An iterator method that applies a function as long as it returns
1521 /// successfully, producing a single, final value.
1523 /// `try_fold()` takes two arguments: an initial value, and a closure with
1524 /// two arguments: an 'accumulator', and an element. The closure either
1525 /// returns successfully, with the value that the accumulator should have
1526 /// for the next iteration, or it returns failure, with an error value that
1527 /// is propagated back to the caller immediately (short-circuiting).
1529 /// The initial value is the value the accumulator will have on the first
1530 /// call. If applying the closure succeeded against every element of the
1531 /// iterator, `try_fold()` returns the final accumulator as success.
1533 /// Folding is useful whenever you have a collection of something, and want
1534 /// to produce a single value from it.
1536 /// # Note to Implementors
1538 /// Most of the other (forward) methods have default implementations in
1539 /// terms of this one, so try to implement this explicitly if it can
1540 /// do something better than the default `for` loop implementation.
1542 /// In particular, try to have this call `try_fold()` on the internal parts
1543 /// from which this iterator is composed. If multiple calls are needed,
1544 /// the `?` operator may be convenient for chaining the accumulator value
1545 /// along, but beware any invariants that need to be upheld before those
1546 /// early returns. This is a `&mut self` method, so iteration needs to be
1547 /// resumable after hitting an error here.
1554 /// let a = [1, 2, 3];
1556 /// // the checked sum of all of the elements of the array
1557 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1559 /// assert_eq!(sum, Some(6));
1562 /// Short-circuiting:
1565 /// let a = [10, 20, 30, 100, 40, 50];
1566 /// let mut it = a.iter();
1568 /// // This sum overflows when adding the 100 element
1569 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1570 /// assert_eq!(sum, None);
1572 /// // Because it short-circuited, the remaining elements are still
1573 /// // available through the iterator.
1574 /// assert_eq!(it.len(), 2);
1575 /// assert_eq!(it.next(), Some(&40));
1578 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1579 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1580 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1582 let mut accum = init;
1583 while let Some(x) = self.next() {
1584 accum = f(accum, x)?;
1589 /// An iterator method that applies a fallible function to each item in the
1590 /// iterator, stopping at the first error and returning that error.
1592 /// This can also be thought of as the fallible form of [`for_each()`]
1593 /// or as the stateless version of [`try_fold()`].
1595 /// [`for_each()`]: #method.for_each
1596 /// [`try_fold()`]: #method.try_fold
1601 /// use std::fs::rename;
1602 /// use std::io::{stdout, Write};
1603 /// use std::path::Path;
1605 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1607 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1608 /// assert!(res.is_ok());
1610 /// let mut it = data.iter().cloned();
1611 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1612 /// assert!(res.is_err());
1613 /// // It short-circuited, so the remaining items are still in the iterator:
1614 /// assert_eq!(it.next(), Some("stale_bread.json"));
1617 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1618 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1619 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1621 self.try_fold((), move |(), x| f(x))
1624 /// An iterator method that applies a function, producing a single, final value.
1626 /// `fold()` takes two arguments: an initial value, and a closure with two
1627 /// arguments: an 'accumulator', and an element. The closure returns the value that
1628 /// the accumulator should have for the next iteration.
1630 /// The initial value is the value the accumulator will have on the first
1633 /// After applying this closure to every element of the iterator, `fold()`
1634 /// returns the accumulator.
1636 /// This operation is sometimes called 'reduce' or 'inject'.
1638 /// Folding is useful whenever you have a collection of something, and want
1639 /// to produce a single value from it.
1641 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1642 /// may not terminate for infinite iterators, even on traits for which a
1643 /// result is determinable in finite time.
1650 /// let a = [1, 2, 3];
1652 /// // the sum of all of the elements of the array
1653 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1655 /// assert_eq!(sum, 6);
1658 /// Let's walk through each step of the iteration here:
1660 /// | element | acc | x | result |
1661 /// |---------|-----|---|--------|
1663 /// | 1 | 0 | 1 | 1 |
1664 /// | 2 | 1 | 2 | 3 |
1665 /// | 3 | 3 | 3 | 6 |
1667 /// And so, our final result, `6`.
1669 /// It's common for people who haven't used iterators a lot to
1670 /// use a `for` loop with a list of things to build up a result. Those
1671 /// can be turned into `fold()`s:
1673 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1676 /// let numbers = [1, 2, 3, 4, 5];
1678 /// let mut result = 0;
1681 /// for i in &numbers {
1682 /// result = result + i;
1686 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1688 /// // they're the same
1689 /// assert_eq!(result, result2);
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1694 Self: Sized, F: FnMut(B, Self::Item) -> B,
1696 self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1699 /// Tests if every element of the iterator matches a predicate.
1701 /// `all()` takes a closure that returns `true` or `false`. It applies
1702 /// this closure to each element of the iterator, and if they all return
1703 /// `true`, then so does `all()`. If any of them return `false`, it
1704 /// returns `false`.
1706 /// `all()` is short-circuiting; in other words, it will stop processing
1707 /// as soon as it finds a `false`, given that no matter what else happens,
1708 /// the result will also be `false`.
1710 /// An empty iterator returns `true`.
1717 /// let a = [1, 2, 3];
1719 /// assert!(a.iter().all(|&x| x > 0));
1721 /// assert!(!a.iter().all(|&x| x > 2));
1724 /// Stopping at the first `false`:
1727 /// let a = [1, 2, 3];
1729 /// let mut iter = a.iter();
1731 /// assert!(!iter.all(|&x| x != 2));
1733 /// // we can still use `iter`, as there are more elements.
1734 /// assert_eq!(iter.next(), Some(&3));
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 fn all<F>(&mut self, mut f: F) -> bool where
1739 Self: Sized, F: FnMut(Self::Item) -> bool
1741 self.try_for_each(move |x| {
1742 if f(x) { LoopState::Continue(()) }
1743 else { LoopState::Break(()) }
1744 }) == LoopState::Continue(())
1747 /// Tests if any element of the iterator matches a predicate.
1749 /// `any()` takes a closure that returns `true` or `false`. It applies
1750 /// this closure to each element of the iterator, and if any of them return
1751 /// `true`, then so does `any()`. If they all return `false`, it
1752 /// returns `false`.
1754 /// `any()` is short-circuiting; in other words, it will stop processing
1755 /// as soon as it finds a `true`, given that no matter what else happens,
1756 /// the result will also be `true`.
1758 /// An empty iterator returns `false`.
1765 /// let a = [1, 2, 3];
1767 /// assert!(a.iter().any(|&x| x > 0));
1769 /// assert!(!a.iter().any(|&x| x > 5));
1772 /// Stopping at the first `true`:
1775 /// let a = [1, 2, 3];
1777 /// let mut iter = a.iter();
1779 /// assert!(iter.any(|&x| x != 2));
1781 /// // we can still use `iter`, as there are more elements.
1782 /// assert_eq!(iter.next(), Some(&2));
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 fn any<F>(&mut self, mut f: F) -> bool where
1788 F: FnMut(Self::Item) -> bool
1790 self.try_for_each(move |x| {
1791 if f(x) { LoopState::Break(()) }
1792 else { LoopState::Continue(()) }
1793 }) == LoopState::Break(())
1796 /// Searches for an element of an iterator that satisfies a predicate.
1798 /// `find()` takes a closure that returns `true` or `false`. It applies
1799 /// this closure to each element of the iterator, and if any of them return
1800 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1801 /// `false`, it returns [`None`].
1803 /// `find()` is short-circuiting; in other words, it will stop processing
1804 /// as soon as the closure returns `true`.
1806 /// Because `find()` takes a reference, and many iterators iterate over
1807 /// references, this leads to a possibly confusing situation where the
1808 /// argument is a double reference. You can see this effect in the
1809 /// examples below, with `&&x`.
1811 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1812 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1819 /// let a = [1, 2, 3];
1821 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1823 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1826 /// Stopping at the first `true`:
1829 /// let a = [1, 2, 3];
1831 /// let mut iter = a.iter();
1833 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1835 /// // we can still use `iter`, as there are more elements.
1836 /// assert_eq!(iter.next(), Some(&3));
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1842 P: FnMut(&Self::Item) -> bool,
1844 self.try_for_each(move |x| {
1845 if predicate(&x) { LoopState::Break(x) }
1846 else { LoopState::Continue(()) }
1850 /// Applies function to the elements of iterator and returns
1851 /// the first non-none result.
1853 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1859 /// let a = ["lol", "NaN", "2", "5"];
1861 /// let first_number = a.iter().find_map(|s| s.parse().ok());
1863 /// assert_eq!(first_number, Some(2));
1866 #[stable(feature = "iterator_find_map", since = "1.30.0")]
1867 fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1869 F: FnMut(Self::Item) -> Option<B>,
1871 self.try_for_each(move |x| {
1873 Some(x) => LoopState::Break(x),
1874 None => LoopState::Continue(()),
1879 /// Searches for an element in an iterator, returning its index.
1881 /// `position()` takes a closure that returns `true` or `false`. It applies
1882 /// this closure to each element of the iterator, and if one of them
1883 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1884 /// them return `false`, it returns [`None`].
1886 /// `position()` is short-circuiting; in other words, it will stop
1887 /// processing as soon as it finds a `true`.
1889 /// # Overflow Behavior
1891 /// The method does no guarding against overflows, so if there are more
1892 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1893 /// result or panics. If debug assertions are enabled, a panic is
1898 /// This function might panic if the iterator has more than `usize::MAX`
1899 /// non-matching elements.
1901 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1902 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1903 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1910 /// let a = [1, 2, 3];
1912 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1914 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1917 /// Stopping at the first `true`:
1920 /// let a = [1, 2, 3, 4];
1922 /// let mut iter = a.iter();
1924 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1926 /// // we can still use `iter`, as there are more elements.
1927 /// assert_eq!(iter.next(), Some(&3));
1929 /// // The returned index depends on iterator state
1930 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1934 #[rustc_inherit_overflow_checks]
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1938 P: FnMut(Self::Item) -> bool,
1940 // The addition might panic on overflow
1941 self.try_fold(0, move |i, x| {
1942 if predicate(x) { LoopState::Break(i) }
1943 else { LoopState::Continue(i + 1) }
1947 /// Searches for an element in an iterator from the right, returning its
1950 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1951 /// this closure to each element of the iterator, starting from the end,
1952 /// and if one of them returns `true`, then `rposition()` returns
1953 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1955 /// `rposition()` is short-circuiting; in other words, it will stop
1956 /// processing as soon as it finds a `true`.
1958 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1959 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1966 /// let a = [1, 2, 3];
1968 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1970 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1973 /// Stopping at the first `true`:
1976 /// let a = [1, 2, 3];
1978 /// let mut iter = a.iter();
1980 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1982 /// // we can still use `iter`, as there are more elements.
1983 /// assert_eq!(iter.next(), Some(&1));
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1988 P: FnMut(Self::Item) -> bool,
1989 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1991 // No need for an overflow check here, because `ExactSizeIterator`
1992 // implies that the number of elements fits into a `usize`.
1994 self.try_rfold(n, move |i, x| {
1996 if predicate(x) { LoopState::Break(i) }
1997 else { LoopState::Continue(i) }
2001 /// Returns the maximum element of an iterator.
2003 /// If several elements are equally maximum, the last element is
2004 /// returned. If the iterator is empty, [`None`] is returned.
2006 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2013 /// let a = [1, 2, 3];
2014 /// let b: Vec<u32> = Vec::new();
2016 /// assert_eq!(a.iter().max(), Some(&3));
2017 /// assert_eq!(b.iter().max(), None);
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2025 // switch to y even if it is only equal, to preserve
2027 |_, x, _, y| *x <= *y)
2031 /// Returns the minimum element of an iterator.
2033 /// If several elements are equally minimum, the first element is
2034 /// returned. If the iterator is empty, [`None`] is returned.
2036 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2043 /// let a = [1, 2, 3];
2044 /// let b: Vec<u32> = Vec::new();
2046 /// assert_eq!(a.iter().min(), Some(&1));
2047 /// assert_eq!(b.iter().min(), None);
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2055 // only switch to y if it is strictly smaller, to
2056 // preserve stability.
2057 |_, x, _, y| *x > *y)
2061 /// Returns the element that gives the maximum value from the
2062 /// specified function.
2064 /// If several elements are equally maximum, the last element is
2065 /// returned. If the iterator is empty, [`None`] is returned.
2067 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2072 /// let a = [-3_i32, 0, 1, 5, -10];
2073 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2076 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2077 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2078 where Self: Sized, F: FnMut(&Self::Item) -> B,
2082 // switch to y even if it is only equal, to preserve
2084 |x_p, _, y_p, _| x_p <= y_p)
2088 /// Returns the element that gives the maximum value with respect to the
2089 /// specified comparison function.
2091 /// If several elements are equally maximum, the last element is
2092 /// returned. If the iterator is empty, [`None`] is returned.
2094 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2099 /// let a = [-3_i32, 0, 1, 5, -10];
2100 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2103 #[stable(feature = "iter_max_by", since = "1.15.0")]
2104 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2105 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2109 // switch to y even if it is only equal, to preserve
2111 |_, x, _, y| Ordering::Greater != compare(x, y))
2115 /// Returns the element that gives the minimum value from the
2116 /// specified function.
2118 /// If several elements are equally minimum, the first element is
2119 /// returned. If the iterator is empty, [`None`] is returned.
2121 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2126 /// let a = [-3_i32, 0, 1, 5, -10];
2127 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2129 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2130 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2131 where Self: Sized, F: FnMut(&Self::Item) -> B,
2135 // only switch to y if it is strictly smaller, to
2136 // preserve stability.
2137 |x_p, _, y_p, _| x_p > y_p)
2141 /// Returns the element that gives the minimum value with respect to the
2142 /// specified comparison function.
2144 /// If several elements are equally minimum, the first element is
2145 /// returned. If the iterator is empty, [`None`] is returned.
2147 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2152 /// let a = [-3_i32, 0, 1, 5, -10];
2153 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2156 #[stable(feature = "iter_min_by", since = "1.15.0")]
2157 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2158 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2162 // switch to y even if it is strictly smaller, to
2163 // preserve stability.
2164 |_, x, _, y| Ordering::Greater == compare(x, y))
2169 /// Reverses an iterator's direction.
2171 /// Usually, iterators iterate from left to right. After using `rev()`,
2172 /// an iterator will instead iterate from right to left.
2174 /// This is only possible if the iterator has an end, so `rev()` only
2175 /// works on [`DoubleEndedIterator`]s.
2177 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2182 /// let a = [1, 2, 3];
2184 /// let mut iter = a.iter().rev();
2186 /// assert_eq!(iter.next(), Some(&3));
2187 /// assert_eq!(iter.next(), Some(&2));
2188 /// assert_eq!(iter.next(), Some(&1));
2190 /// assert_eq!(iter.next(), None);
2193 #[stable(feature = "rust1", since = "1.0.0")]
2194 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2198 /// Converts an iterator of pairs into a pair of containers.
2200 /// `unzip()` consumes an entire iterator of pairs, producing two
2201 /// collections: one from the left elements of the pairs, and one
2202 /// from the right elements.
2204 /// This function is, in some sense, the opposite of [`zip`].
2206 /// [`zip`]: #method.zip
2213 /// let a = [(1, 2), (3, 4)];
2215 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2217 /// assert_eq!(left, [1, 3]);
2218 /// assert_eq!(right, [2, 4]);
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2222 FromA: Default + Extend<A>,
2223 FromB: Default + Extend<B>,
2224 Self: Sized + Iterator<Item=(A, B)>,
2226 let mut ts: FromA = Default::default();
2227 let mut us: FromB = Default::default();
2229 self.for_each(|(t, u)| {
2237 /// Creates an iterator which [`clone`]s all of its elements.
2239 /// This is useful when you have an iterator over `&T`, but you need an
2240 /// iterator over `T`.
2242 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2249 /// let a = [1, 2, 3];
2251 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2253 /// // cloned is the same as .map(|&x| x), for integers
2254 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2256 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2257 /// assert_eq!(v_map, vec![1, 2, 3]);
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2261 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2266 /// Repeats an iterator endlessly.
2268 /// Instead of stopping at [`None`], the iterator will instead start again,
2269 /// from the beginning. After iterating again, it will start at the
2270 /// beginning again. And again. And again. Forever.
2272 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2279 /// let a = [1, 2, 3];
2281 /// let mut it = a.iter().cycle();
2283 /// assert_eq!(it.next(), Some(&1));
2284 /// assert_eq!(it.next(), Some(&2));
2285 /// assert_eq!(it.next(), Some(&3));
2286 /// assert_eq!(it.next(), Some(&1));
2287 /// assert_eq!(it.next(), Some(&2));
2288 /// assert_eq!(it.next(), Some(&3));
2289 /// assert_eq!(it.next(), Some(&1));
2291 #[stable(feature = "rust1", since = "1.0.0")]
2293 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2294 Cycle{orig: self.clone(), iter: self}
2297 /// Sums the elements of an iterator.
2299 /// Takes each element, adds them together, and returns the result.
2301 /// An empty iterator returns the zero value of the type.
2305 /// When calling `sum()` and a primitive integer type is being returned, this
2306 /// method will panic if the computation overflows and debug assertions are
2314 /// let a = [1, 2, 3];
2315 /// let sum: i32 = a.iter().sum();
2317 /// assert_eq!(sum, 6);
2319 #[stable(feature = "iter_arith", since = "1.11.0")]
2320 fn sum<S>(self) -> S
2327 /// Iterates over the entire iterator, multiplying all the elements
2329 /// An empty iterator returns the one value of the type.
2333 /// When calling `product()` and a primitive integer type is being returned,
2334 /// method will panic if the computation overflows and debug assertions are
2340 /// fn factorial(n: u32) -> u32 {
2341 /// (1..).take_while(|&i| i <= n).product()
2343 /// assert_eq!(factorial(0), 1);
2344 /// assert_eq!(factorial(1), 1);
2345 /// assert_eq!(factorial(5), 120);
2347 #[stable(feature = "iter_arith", since = "1.11.0")]
2348 fn product<P>(self) -> P
2350 P: Product<Self::Item>,
2352 Product::product(self)
2355 /// Lexicographically compares the elements of this `Iterator` with those
2357 #[stable(feature = "iter_order", since = "1.5.0")]
2358 fn cmp<I>(mut self, other: I) -> Ordering where
2359 I: IntoIterator<Item = Self::Item>,
2363 let mut other = other.into_iter();
2366 let x = match self.next() {
2367 None => if other.next().is_none() {
2368 return Ordering::Equal
2370 return Ordering::Less
2375 let y = match other.next() {
2376 None => return Ordering::Greater,
2381 Ordering::Equal => (),
2382 non_eq => return non_eq,
2387 /// Lexicographically compares the elements of this `Iterator` with those
2389 #[stable(feature = "iter_order", since = "1.5.0")]
2390 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2392 Self::Item: PartialOrd<I::Item>,
2395 let mut other = other.into_iter();
2398 let x = match self.next() {
2399 None => if other.next().is_none() {
2400 return Some(Ordering::Equal)
2402 return Some(Ordering::Less)
2407 let y = match other.next() {
2408 None => return Some(Ordering::Greater),
2412 match x.partial_cmp(&y) {
2413 Some(Ordering::Equal) => (),
2414 non_eq => return non_eq,
2419 /// Determines if the elements of this `Iterator` are equal to those of
2421 #[stable(feature = "iter_order", since = "1.5.0")]
2422 fn eq<I>(mut self, other: I) -> bool where
2424 Self::Item: PartialEq<I::Item>,
2427 let mut other = other.into_iter();
2430 let x = match self.next() {
2431 None => return other.next().is_none(),
2435 let y = match other.next() {
2436 None => return false,
2440 if x != y { return false }
2444 /// Determines if the elements of this `Iterator` are unequal to those of
2446 #[stable(feature = "iter_order", since = "1.5.0")]
2447 fn ne<I>(mut self, other: I) -> bool where
2449 Self::Item: PartialEq<I::Item>,
2452 let mut other = other.into_iter();
2455 let x = match self.next() {
2456 None => return other.next().is_some(),
2460 let y = match other.next() {
2461 None => return true,
2465 if x != y { return true }
2469 /// Determines if the elements of this `Iterator` are lexicographically
2470 /// less than those of another.
2471 #[stable(feature = "iter_order", since = "1.5.0")]
2472 fn lt<I>(mut self, other: I) -> bool where
2474 Self::Item: PartialOrd<I::Item>,
2477 let mut other = other.into_iter();
2480 let x = match self.next() {
2481 None => return other.next().is_some(),
2485 let y = match other.next() {
2486 None => return false,
2490 match x.partial_cmp(&y) {
2491 Some(Ordering::Less) => return true,
2492 Some(Ordering::Equal) => (),
2493 Some(Ordering::Greater) => return false,
2494 None => return false,
2499 /// Determines if the elements of this `Iterator` are lexicographically
2500 /// less or equal to those of another.
2501 #[stable(feature = "iter_order", since = "1.5.0")]
2502 fn le<I>(mut self, other: I) -> bool where
2504 Self::Item: PartialOrd<I::Item>,
2507 let mut other = other.into_iter();
2510 let x = match self.next() {
2511 None => { other.next(); return true; },
2515 let y = match other.next() {
2516 None => return false,
2520 match x.partial_cmp(&y) {
2521 Some(Ordering::Less) => return true,
2522 Some(Ordering::Equal) => (),
2523 Some(Ordering::Greater) => return false,
2524 None => return false,
2529 /// Determines if the elements of this `Iterator` are lexicographically
2530 /// greater than those of another.
2531 #[stable(feature = "iter_order", since = "1.5.0")]
2532 fn gt<I>(mut self, other: I) -> bool where
2534 Self::Item: PartialOrd<I::Item>,
2537 let mut other = other.into_iter();
2540 let x = match self.next() {
2541 None => { other.next(); return false; },
2545 let y = match other.next() {
2546 None => return true,
2550 match x.partial_cmp(&y) {
2551 Some(Ordering::Less) => return false,
2552 Some(Ordering::Equal) => (),
2553 Some(Ordering::Greater) => return true,
2554 None => return false,
2559 /// Determines if the elements of this `Iterator` are lexicographically
2560 /// greater than or equal to those of another.
2561 #[stable(feature = "iter_order", since = "1.5.0")]
2562 fn ge<I>(mut self, other: I) -> bool where
2564 Self::Item: PartialOrd<I::Item>,
2567 let mut other = other.into_iter();
2570 let x = match self.next() {
2571 None => return other.next().is_none(),
2575 let y = match other.next() {
2576 None => return true,
2580 match x.partial_cmp(&y) {
2581 Some(Ordering::Less) => return false,
2582 Some(Ordering::Equal) => (),
2583 Some(Ordering::Greater) => return true,
2584 None => return false,
2590 /// Select an element from an iterator based on the given "projection"
2591 /// and "comparison" function.
2593 /// This is an idiosyncratic helper to try to factor out the
2594 /// commonalities of {max,min}{,_by}. In particular, this avoids
2595 /// having to implement optimizations several times.
2597 fn select_fold1<I, B, FProj, FCmp>(mut it: I,
2599 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2601 FProj: FnMut(&I::Item) -> B,
2602 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2604 // start with the first element as our selection. This avoids
2605 // having to use `Option`s inside the loop, translating to a
2606 // sizeable performance gain (6x in one case).
2607 it.next().map(|first| {
2608 let first_p = f_proj(&first);
2610 it.fold((first_p, first), |(sel_p, sel), x| {
2611 let x_p = f_proj(&x);
2612 if f_cmp(&sel_p, &sel, &x_p, &x) {
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<I: Iterator + ?Sized> Iterator for &mut I {
2623 type Item = I::Item;
2624 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2625 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2626 fn nth(&mut self, n: usize) -> Option<Self::Item> {