1 use crate::cmp::Ordering;
4 use super::super::LoopState;
5 use super::super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse};
6 use super::super::{Flatten, FlatMap};
7 use super::super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
8 use super::super::{Zip, Sum, Product, FromIterator};
10 fn _assert_is_object_safe(_: &dyn Iterator<Item=()>) {}
12 /// An interface for dealing with iterators.
14 /// This is the main iterator trait. For more about the concept of iterators
15 /// generally, please see the [module-level documentation]. In particular, you
16 /// may want to know how to [implement `Iterator`][impl].
18 /// [module-level documentation]: index.html
19 /// [impl]: index.html#implementing-iterator
20 #[stable(feature = "rust1", since = "1.0.0")]
21 #[rustc_on_unimplemented(
23 _Self="[std::ops::Range<Idx>; 1]",
24 label="if you meant to iterate between two values, remove the square brackets",
25 note="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
26 without the brackets: `start..end`"
29 _Self="[std::ops::RangeFrom<Idx>; 1]",
30 label="if you meant to iterate from a value onwards, remove the square brackets",
31 note="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
32 `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
33 unbounded iterator will run forever unless you `break` or `return` from within the \
37 _Self="[std::ops::RangeTo<Idx>; 1]",
38 label="if you meant to iterate until a value, remove the square brackets and add a \
40 note="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
41 `Range` without the brackets: `0..end`"
44 _Self="[std::ops::RangeInclusive<Idx>; 1]",
45 label="if you meant to iterate between two values, remove the square brackets",
46 note="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
47 `RangeInclusive` without the brackets: `start..=end`"
50 _Self="[std::ops::RangeToInclusive<Idx>; 1]",
51 label="if you meant to iterate until a value (including it), remove the square brackets \
52 and add a starting value",
53 note="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
54 bounded `RangeInclusive` without the brackets: `0..=end`"
57 _Self="std::ops::RangeTo<Idx>",
58 label="if you meant to iterate until a value, add a starting value",
59 note="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
60 bounded `Range`: `0..end`"
63 _Self="std::ops::RangeToInclusive<Idx>",
64 label="if you meant to iterate until a value (including it), add a starting value",
65 note="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
66 to have a bounded `RangeInclusive`: `0..=end`"
70 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
73 _Self="std::string::String",
74 label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
78 label="borrow the array with `&` or call `.iter()` on it to iterate over it",
79 note="arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
83 note="if you want to iterate between `start` until a value `end`, use the exclusive range \
84 syntax `start..end` or the inclusive range syntax `start..=end`"
86 label="`{Self}` is not an iterator",
87 message="`{Self}` is not an iterator"
90 #[must_use = "iterators are lazy and do nothing unless consumed"]
92 /// The type of the elements being iterated over.
93 #[stable(feature = "rust1", since = "1.0.0")]
96 /// Advances the iterator and returns the next value.
98 /// Returns [`None`] when iteration is finished. Individual iterator
99 /// implementations may choose to resume iteration, and so calling `next()`
100 /// again may or may not eventually start returning [`Some(Item)`] again at some
103 /// [`None`]: ../../std/option/enum.Option.html#variant.None
104 /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
111 /// let a = [1, 2, 3];
113 /// let mut iter = a.iter();
115 /// // A call to next() returns the next value...
116 /// assert_eq!(Some(&1), iter.next());
117 /// assert_eq!(Some(&2), iter.next());
118 /// assert_eq!(Some(&3), iter.next());
120 /// // ... and then None once it's over.
121 /// assert_eq!(None, iter.next());
123 /// // More calls may or may not return `None`. Here, they always will.
124 /// assert_eq!(None, iter.next());
125 /// assert_eq!(None, iter.next());
127 #[stable(feature = "rust1", since = "1.0.0")]
128 fn next(&mut self) -> Option<Self::Item>;
130 /// Returns the bounds on the remaining length of the iterator.
132 /// Specifically, `size_hint()` returns a tuple where the first element
133 /// is the lower bound, and the second element is the upper bound.
135 /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
136 /// A [`None`] here means that either there is no known upper bound, or the
137 /// upper bound is larger than [`usize`].
139 /// # Implementation notes
141 /// It is not enforced that an iterator implementation yields the declared
142 /// number of elements. A buggy iterator may yield less than the lower bound
143 /// or more than the upper bound of elements.
145 /// `size_hint()` is primarily intended to be used for optimizations such as
146 /// reserving space for the elements of the iterator, but must not be
147 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
148 /// implementation of `size_hint()` should not lead to memory safety
151 /// That said, the implementation should provide a correct estimation,
152 /// because otherwise it would be a violation of the trait's protocol.
154 /// The default implementation returns `(0, `[`None`]`)` which is correct for any
157 /// [`usize`]: ../../std/primitive.usize.html
158 /// [`Option`]: ../../std/option/enum.Option.html
159 /// [`None`]: ../../std/option/enum.Option.html#variant.None
166 /// let a = [1, 2, 3];
167 /// let iter = a.iter();
169 /// assert_eq!((3, Some(3)), iter.size_hint());
172 /// A more complex example:
175 /// // The even numbers from zero to ten.
176 /// let iter = (0..10).filter(|x| x % 2 == 0);
178 /// // We might iterate from zero to ten times. Knowing that it's five
179 /// // exactly wouldn't be possible without executing filter().
180 /// assert_eq!((0, Some(10)), iter.size_hint());
182 /// // Let's add five more numbers with chain()
183 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
185 /// // now both bounds are increased by five
186 /// assert_eq!((5, Some(15)), iter.size_hint());
189 /// Returning `None` for an upper bound:
192 /// // an infinite iterator has no upper bound
193 /// // and the maximum possible lower bound
196 /// assert_eq!((usize::max_value(), None), iter.size_hint());
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
202 /// Consumes the iterator, counting the number of iterations and returning it.
204 /// This method will evaluate the iterator until its [`next`] returns
205 /// [`None`]. Once [`None`] is encountered, `count()` returns the number of
206 /// times it called [`next`].
208 /// [`next`]: #tymethod.next
209 /// [`None`]: ../../std/option/enum.Option.html#variant.None
211 /// # Overflow Behavior
213 /// The method does no guarding against overflows, so counting elements of
214 /// an iterator with more than [`usize::MAX`] elements either produces the
215 /// wrong result or panics. If debug assertions are enabled, a panic is
220 /// This function might panic if the iterator has more than [`usize::MAX`]
223 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
230 /// let a = [1, 2, 3];
231 /// assert_eq!(a.iter().count(), 3);
233 /// let a = [1, 2, 3, 4, 5];
234 /// assert_eq!(a.iter().count(), 5);
237 #[rustc_inherit_overflow_checks]
238 #[stable(feature = "rust1", since = "1.0.0")]
239 fn count(self) -> usize where Self: Sized {
241 self.fold(0, |cnt, _| cnt + 1)
244 /// Consumes the iterator, returning the last element.
246 /// This method will evaluate the iterator until it returns [`None`]. While
247 /// doing so, it keeps track of the current element. After [`None`] is
248 /// returned, `last()` will then return the last element it saw.
250 /// [`None`]: ../../std/option/enum.Option.html#variant.None
257 /// let a = [1, 2, 3];
258 /// assert_eq!(a.iter().last(), Some(&3));
260 /// let a = [1, 2, 3, 4, 5];
261 /// assert_eq!(a.iter().last(), Some(&5));
264 #[stable(feature = "rust1", since = "1.0.0")]
265 fn last(self) -> Option<Self::Item> where Self: Sized {
267 for x in self { last = Some(x); }
271 /// Returns the `n`th element of the iterator.
273 /// Like most indexing operations, the count starts from zero, so `nth(0)`
274 /// returns the first value, `nth(1)` the second, and so on.
276 /// Note that all preceding elements, as well as the returned element, will be
277 /// consumed from the iterator. That means that the preceding elements will be
278 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
279 /// will return different elements.
281 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
284 /// [`None`]: ../../std/option/enum.Option.html#variant.None
291 /// let a = [1, 2, 3];
292 /// assert_eq!(a.iter().nth(1), Some(&2));
295 /// Calling `nth()` multiple times doesn't rewind the iterator:
298 /// let a = [1, 2, 3];
300 /// let mut iter = a.iter();
302 /// assert_eq!(iter.nth(1), Some(&2));
303 /// assert_eq!(iter.nth(1), None);
306 /// Returning `None` if there are less than `n + 1` elements:
309 /// let a = [1, 2, 3];
310 /// assert_eq!(a.iter().nth(10), None);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
316 if n == 0 { return Some(x) }
322 /// Creates an iterator starting at the same point, but stepping by
323 /// the given amount at each iteration.
325 /// Note 1: The first element of the iterator will always be returned,
326 /// regardless of the step given.
328 /// Note 2: The time at which ignored elements are pulled is not fixed.
329 /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
330 /// but is also free to behave like the sequence
331 /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
332 /// Which way is used may change for some iterators for performance reasons.
333 /// The second way will advance the iterator earlier and may consume more items.
335 /// `advance_n_and_return_first` is the equivalent of:
337 /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
341 /// let next = iter.next();
342 /// if total_step > 1 {
343 /// iter.nth(total_step-2);
351 /// The method will panic if the given step is `0`.
358 /// let a = [0, 1, 2, 3, 4, 5];
359 /// let mut iter = a.into_iter().step_by(2);
361 /// assert_eq!(iter.next(), Some(&0));
362 /// assert_eq!(iter.next(), Some(&2));
363 /// assert_eq!(iter.next(), Some(&4));
364 /// assert_eq!(iter.next(), None);
367 #[stable(feature = "iterator_step_by", since = "1.28.0")]
368 fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
369 StepBy::new(self, step)
372 /// Takes two iterators and creates a new iterator over both in sequence.
374 /// `chain()` will return a new iterator which will first iterate over
375 /// values from the first iterator and then over values from the second
378 /// In other words, it links two iterators together, in a chain. 🔗
385 /// let a1 = [1, 2, 3];
386 /// let a2 = [4, 5, 6];
388 /// let mut iter = a1.iter().chain(a2.iter());
390 /// assert_eq!(iter.next(), Some(&1));
391 /// assert_eq!(iter.next(), Some(&2));
392 /// assert_eq!(iter.next(), Some(&3));
393 /// assert_eq!(iter.next(), Some(&4));
394 /// assert_eq!(iter.next(), Some(&5));
395 /// assert_eq!(iter.next(), Some(&6));
396 /// assert_eq!(iter.next(), None);
399 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
400 /// anything that can be converted into an [`Iterator`], not just an
401 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
402 /// [`IntoIterator`], and so can be passed to `chain()` directly:
404 /// [`IntoIterator`]: trait.IntoIterator.html
405 /// [`Iterator`]: trait.Iterator.html
408 /// let s1 = &[1, 2, 3];
409 /// let s2 = &[4, 5, 6];
411 /// let mut iter = s1.iter().chain(s2);
413 /// assert_eq!(iter.next(), Some(&1));
414 /// assert_eq!(iter.next(), Some(&2));
415 /// assert_eq!(iter.next(), Some(&3));
416 /// assert_eq!(iter.next(), Some(&4));
417 /// assert_eq!(iter.next(), Some(&5));
418 /// assert_eq!(iter.next(), Some(&6));
419 /// assert_eq!(iter.next(), None);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
424 Self: Sized, U: IntoIterator<Item=Self::Item>,
426 Chain::new(self, other.into_iter())
429 /// 'Zips up' two iterators into a single iterator of pairs.
431 /// `zip()` returns a new iterator that will iterate over two other
432 /// iterators, returning a tuple where the first element comes from the
433 /// first iterator, and the second element comes from the second iterator.
435 /// In other words, it zips two iterators together, into a single one.
437 /// If either iterator returns [`None`], [`next`] from the zipped iterator
438 /// will return [`None`]. If the first iterator returns [`None`], `zip` will
439 /// short-circuit and `next` will not be called on the second iterator.
446 /// let a1 = [1, 2, 3];
447 /// let a2 = [4, 5, 6];
449 /// let mut iter = a1.iter().zip(a2.iter());
451 /// assert_eq!(iter.next(), Some((&1, &4)));
452 /// assert_eq!(iter.next(), Some((&2, &5)));
453 /// assert_eq!(iter.next(), Some((&3, &6)));
454 /// assert_eq!(iter.next(), None);
457 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
458 /// anything that can be converted into an [`Iterator`], not just an
459 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
460 /// [`IntoIterator`], and so can be passed to `zip()` directly:
462 /// [`IntoIterator`]: trait.IntoIterator.html
463 /// [`Iterator`]: trait.Iterator.html
466 /// let s1 = &[1, 2, 3];
467 /// let s2 = &[4, 5, 6];
469 /// let mut iter = s1.iter().zip(s2);
471 /// assert_eq!(iter.next(), Some((&1, &4)));
472 /// assert_eq!(iter.next(), Some((&2, &5)));
473 /// assert_eq!(iter.next(), Some((&3, &6)));
474 /// assert_eq!(iter.next(), None);
477 /// `zip()` is often used to zip an infinite iterator to a finite one.
478 /// This works because the finite iterator will eventually return [`None`],
479 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
482 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
484 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
486 /// assert_eq!((0, 'f'), enumerate[0]);
487 /// assert_eq!((0, 'f'), zipper[0]);
489 /// assert_eq!((1, 'o'), enumerate[1]);
490 /// assert_eq!((1, 'o'), zipper[1]);
492 /// assert_eq!((2, 'o'), enumerate[2]);
493 /// assert_eq!((2, 'o'), zipper[2]);
496 /// [`enumerate`]: trait.Iterator.html#method.enumerate
497 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
498 /// [`None`]: ../../std/option/enum.Option.html#variant.None
500 #[stable(feature = "rust1", since = "1.0.0")]
501 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
502 Self: Sized, U: IntoIterator
504 Zip::new(self, other.into_iter())
507 /// Takes a closure and creates an iterator which calls that closure on each
510 /// `map()` transforms one iterator into another, by means of its argument:
511 /// something that implements [`FnMut`]. It produces a new iterator which
512 /// calls this closure on each element of the original iterator.
514 /// If you are good at thinking in types, you can think of `map()` like this:
515 /// If you have an iterator that gives you elements of some type `A`, and
516 /// you want an iterator of some other type `B`, you can use `map()`,
517 /// passing a closure that takes an `A` and returns a `B`.
519 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
520 /// lazy, it is best used when you're already working with other iterators.
521 /// If you're doing some sort of looping for a side effect, it's considered
522 /// more idiomatic to use [`for`] than `map()`.
524 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
525 /// [`FnMut`]: ../../std/ops/trait.FnMut.html
532 /// let a = [1, 2, 3];
534 /// let mut iter = a.into_iter().map(|x| 2 * x);
536 /// assert_eq!(iter.next(), Some(2));
537 /// assert_eq!(iter.next(), Some(4));
538 /// assert_eq!(iter.next(), Some(6));
539 /// assert_eq!(iter.next(), None);
542 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
545 /// # #![allow(unused_must_use)]
546 /// // don't do this:
547 /// (0..5).map(|x| println!("{}", x));
549 /// // it won't even execute, as it is lazy. Rust will warn you about this.
551 /// // Instead, use for:
553 /// println!("{}", x);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 fn map<B, F>(self, f: F) -> Map<Self, F> where
559 Self: Sized, F: FnMut(Self::Item) -> B,
564 /// Calls a closure on each element of an iterator.
566 /// This is equivalent to using a [`for`] loop on the iterator, although
567 /// `break` and `continue` are not possible from a closure. It's generally
568 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
569 /// when processing items at the end of longer iterator chains. In some
570 /// cases `for_each` may also be faster than a loop, because it will use
571 /// internal iteration on adaptors like `Chain`.
573 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
580 /// use std::sync::mpsc::channel;
582 /// let (tx, rx) = channel();
583 /// (0..5).map(|x| x * 2 + 1)
584 /// .for_each(move |x| tx.send(x).unwrap());
586 /// let v: Vec<_> = rx.iter().collect();
587 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
590 /// For such a small example, a `for` loop may be cleaner, but `for_each`
591 /// might be preferable to keep a functional style with longer iterators:
594 /// (0..5).flat_map(|x| x * 100 .. x * 110)
596 /// .filter(|&(i, x)| (i + x) % 3 == 0)
597 /// .for_each(|(i, x)| println!("{}:{}", i, x));
600 #[stable(feature = "iterator_for_each", since = "1.21.0")]
601 fn for_each<F>(self, mut f: F) where
602 Self: Sized, F: FnMut(Self::Item),
604 self.fold((), move |(), item| f(item));
607 /// Creates an iterator which uses a closure to determine if an element
608 /// should be yielded.
610 /// The closure must return `true` or `false`. `filter()` creates an
611 /// iterator which calls this closure on each element. If the closure
612 /// returns `true`, then the element is returned. If the closure returns
613 /// `false`, it will try again, and call the closure on the next element,
614 /// seeing if it passes the test.
621 /// let a = [0i32, 1, 2];
623 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
625 /// assert_eq!(iter.next(), Some(&1));
626 /// assert_eq!(iter.next(), Some(&2));
627 /// assert_eq!(iter.next(), None);
630 /// Because the closure passed to `filter()` takes a reference, and many
631 /// iterators iterate over references, this leads to a possibly confusing
632 /// situation, where the type of the closure is a double reference:
635 /// let a = [0, 1, 2];
637 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
639 /// assert_eq!(iter.next(), Some(&2));
640 /// assert_eq!(iter.next(), None);
643 /// It's common to instead use destructuring on the argument to strip away
647 /// let a = [0, 1, 2];
649 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
651 /// assert_eq!(iter.next(), Some(&2));
652 /// assert_eq!(iter.next(), None);
658 /// let a = [0, 1, 2];
660 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
662 /// assert_eq!(iter.next(), Some(&2));
663 /// assert_eq!(iter.next(), None);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
670 Self: Sized, P: FnMut(&Self::Item) -> bool,
672 Filter::new(self, predicate)
675 /// Creates an iterator that both filters and maps.
677 /// The closure must return an [`Option<T>`]. `filter_map` creates an
678 /// iterator which calls this closure on each element. If the closure
679 /// returns [`Some(element)`][`Some`], then that element is returned. If the
680 /// closure returns [`None`], it will try again, and call the closure on the
681 /// next element, seeing if it will return [`Some`].
683 /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
686 /// [`filter`]: #method.filter
687 /// [`map`]: #method.map
689 /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
691 /// In other words, it removes the [`Option<T>`] layer automatically. If your
692 /// mapping is already returning an [`Option<T>`] and you want to skip over
693 /// [`None`]s, then `filter_map` is much, much nicer to use.
700 /// let a = ["1", "lol", "3", "NaN", "5"];
702 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
704 /// assert_eq!(iter.next(), Some(1));
705 /// assert_eq!(iter.next(), Some(3));
706 /// assert_eq!(iter.next(), Some(5));
707 /// assert_eq!(iter.next(), None);
710 /// Here's the same example, but with [`filter`] and [`map`]:
713 /// let a = ["1", "lol", "3", "NaN", "5"];
714 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
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 /// [`Option<T>`]: ../../std/option/enum.Option.html
722 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
723 /// [`None`]: ../../std/option/enum.Option.html#variant.None
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
727 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
729 FilterMap::new(self, f)
732 /// Creates an iterator which gives the current iteration count as well as
735 /// The iterator returned yields pairs `(i, val)`, where `i` is the
736 /// current index of iteration and `val` is the value returned by the
739 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
740 /// different sized integer, the [`zip`] function provides similar
743 /// # Overflow Behavior
745 /// The method does no guarding against overflows, so enumerating more than
746 /// [`usize::MAX`] elements either produces the wrong result or panics. If
747 /// debug assertions are enabled, a panic is guaranteed.
751 /// The returned iterator might panic if the to-be-returned index would
752 /// overflow a [`usize`].
754 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
755 /// [`usize`]: ../../std/primitive.usize.html
756 /// [`zip`]: #method.zip
761 /// let a = ['a', 'b', 'c'];
763 /// let mut iter = a.iter().enumerate();
765 /// assert_eq!(iter.next(), Some((0, &'a')));
766 /// assert_eq!(iter.next(), Some((1, &'b')));
767 /// assert_eq!(iter.next(), Some((2, &'c')));
768 /// assert_eq!(iter.next(), None);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
776 /// Creates an iterator which can use `peek` to look at the next element of
777 /// the iterator without consuming it.
779 /// Adds a [`peek`] method to an iterator. See its documentation for
780 /// more information.
782 /// Note that the underlying iterator is still advanced when [`peek`] is
783 /// called for the first time: In order to retrieve the next element,
784 /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
785 /// anything other than fetching the next value) of the [`next`] method
788 /// [`peek`]: struct.Peekable.html#method.peek
789 /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
796 /// let xs = [1, 2, 3];
798 /// let mut iter = xs.iter().peekable();
800 /// // peek() lets us see into the future
801 /// assert_eq!(iter.peek(), Some(&&1));
802 /// assert_eq!(iter.next(), Some(&1));
804 /// assert_eq!(iter.next(), Some(&2));
806 /// // we can peek() multiple times, the iterator won't advance
807 /// assert_eq!(iter.peek(), Some(&&3));
808 /// assert_eq!(iter.peek(), Some(&&3));
810 /// assert_eq!(iter.next(), Some(&3));
812 /// // after the iterator is finished, so is peek()
813 /// assert_eq!(iter.peek(), None);
814 /// assert_eq!(iter.next(), None);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 fn peekable(self) -> Peekable<Self> where Self: Sized {
822 /// Creates an iterator that [`skip`]s elements based on a predicate.
824 /// [`skip`]: #method.skip
826 /// `skip_while()` takes a closure as an argument. It will call this
827 /// closure on each element of the iterator, and ignore elements
828 /// until it returns `false`.
830 /// After `false` is returned, `skip_while()`'s job is over, and the
831 /// rest of the elements are yielded.
838 /// let a = [-1i32, 0, 1];
840 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
842 /// assert_eq!(iter.next(), Some(&0));
843 /// assert_eq!(iter.next(), Some(&1));
844 /// assert_eq!(iter.next(), None);
847 /// Because the closure passed to `skip_while()` takes a reference, and many
848 /// iterators iterate over references, this leads to a possibly confusing
849 /// situation, where the type of the closure is a double reference:
852 /// let a = [-1, 0, 1];
854 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
856 /// assert_eq!(iter.next(), Some(&0));
857 /// assert_eq!(iter.next(), Some(&1));
858 /// assert_eq!(iter.next(), None);
861 /// Stopping after an initial `false`:
864 /// let a = [-1, 0, 1, -2];
866 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
868 /// assert_eq!(iter.next(), Some(&0));
869 /// assert_eq!(iter.next(), Some(&1));
871 /// // while this would have been false, since we already got a false,
872 /// // skip_while() isn't used any more
873 /// assert_eq!(iter.next(), Some(&-2));
875 /// assert_eq!(iter.next(), None);
878 #[stable(feature = "rust1", since = "1.0.0")]
879 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
880 Self: Sized, P: FnMut(&Self::Item) -> bool,
882 SkipWhile::new(self, predicate)
885 /// Creates an iterator that yields elements based on a predicate.
887 /// `take_while()` takes a closure as an argument. It will call this
888 /// closure on each element of the iterator, and yield elements
889 /// while it returns `true`.
891 /// After `false` is returned, `take_while()`'s job is over, and the
892 /// rest of the elements are ignored.
899 /// let a = [-1i32, 0, 1];
901 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
903 /// assert_eq!(iter.next(), Some(&-1));
904 /// assert_eq!(iter.next(), None);
907 /// Because the closure passed to `take_while()` takes a reference, and many
908 /// iterators iterate over references, this leads to a possibly confusing
909 /// situation, where the type of the closure is a double reference:
912 /// let a = [-1, 0, 1];
914 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
916 /// assert_eq!(iter.next(), Some(&-1));
917 /// assert_eq!(iter.next(), None);
920 /// Stopping after an initial `false`:
923 /// let a = [-1, 0, 1, -2];
925 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
927 /// assert_eq!(iter.next(), Some(&-1));
929 /// // We have more elements that are less than zero, but since we already
930 /// // got a false, take_while() isn't used any more
931 /// assert_eq!(iter.next(), None);
934 /// Because `take_while()` needs to look at the value in order to see if it
935 /// should be included or not, consuming iterators will see that it is
939 /// let a = [1, 2, 3, 4];
940 /// let mut iter = a.into_iter();
942 /// let result: Vec<i32> = iter.by_ref()
943 /// .take_while(|n| **n != 3)
947 /// assert_eq!(result, &[1, 2]);
949 /// let result: Vec<i32> = iter.cloned().collect();
951 /// assert_eq!(result, &[4]);
954 /// The `3` is no longer there, because it was consumed in order to see if
955 /// the iteration should stop, but wasn't placed back into the iterator.
957 #[stable(feature = "rust1", since = "1.0.0")]
958 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
959 Self: Sized, P: FnMut(&Self::Item) -> bool,
961 TakeWhile::new(self, predicate)
964 /// Creates an iterator that skips the first `n` elements.
966 /// After they have been consumed, the rest of the elements are yielded.
973 /// let a = [1, 2, 3];
975 /// let mut iter = a.iter().skip(2);
977 /// assert_eq!(iter.next(), Some(&3));
978 /// assert_eq!(iter.next(), None);
981 #[stable(feature = "rust1", since = "1.0.0")]
982 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
986 /// Creates an iterator that yields its first `n` elements.
993 /// let a = [1, 2, 3];
995 /// let mut iter = a.iter().take(2);
997 /// assert_eq!(iter.next(), Some(&1));
998 /// assert_eq!(iter.next(), Some(&2));
999 /// assert_eq!(iter.next(), None);
1002 /// `take()` is often used with an infinite iterator, to make it finite:
1005 /// let mut iter = (0..).take(3);
1007 /// assert_eq!(iter.next(), Some(0));
1008 /// assert_eq!(iter.next(), Some(1));
1009 /// assert_eq!(iter.next(), Some(2));
1010 /// assert_eq!(iter.next(), None);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1018 /// An iterator adaptor similar to [`fold`] that holds internal state and
1019 /// produces a new iterator.
1021 /// [`fold`]: #method.fold
1023 /// `scan()` takes two arguments: an initial value which seeds the internal
1024 /// state, and a closure with two arguments, the first being a mutable
1025 /// reference to the internal state and the second an iterator element.
1026 /// The closure can assign to the internal state to share state between
1029 /// On iteration, the closure will be applied to each element of the
1030 /// iterator and the return value from the closure, an [`Option`], is
1031 /// yielded by the iterator.
1033 /// [`Option`]: ../../std/option/enum.Option.html
1040 /// let a = [1, 2, 3];
1042 /// let mut iter = a.iter().scan(1, |state, &x| {
1043 /// // each iteration, we'll multiply the state by the element
1044 /// *state = *state * x;
1046 /// // then, we'll yield the negation of the state
1050 /// assert_eq!(iter.next(), Some(-1));
1051 /// assert_eq!(iter.next(), Some(-2));
1052 /// assert_eq!(iter.next(), Some(-6));
1053 /// assert_eq!(iter.next(), None);
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1058 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1060 Scan::new(self, initial_state, f)
1063 /// Creates an iterator that works like map, but flattens nested structure.
1065 /// The [`map`] adapter is very useful, but only when the closure
1066 /// argument produces values. If it produces an iterator instead, there's
1067 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1070 /// You can think of `flat_map(f)` as the semantic equivalent
1071 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1073 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1074 /// one item for each element, and `flat_map()`'s closure returns an
1075 /// iterator for each element.
1077 /// [`map`]: #method.map
1078 /// [`flatten`]: #method.flatten
1085 /// let words = ["alpha", "beta", "gamma"];
1087 /// // chars() returns an iterator
1088 /// let merged: String = words.iter()
1089 /// .flat_map(|s| s.chars())
1091 /// assert_eq!(merged, "alphabetagamma");
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1096 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1098 FlatMap::new(self, f)
1101 /// Creates an iterator that flattens nested structure.
1103 /// This is useful when you have an iterator of iterators or an iterator of
1104 /// things that can be turned into iterators and you want to remove one
1105 /// level of indirection.
1112 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1113 /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1114 /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1117 /// Mapping and then flattening:
1120 /// let words = ["alpha", "beta", "gamma"];
1122 /// // chars() returns an iterator
1123 /// let merged: String = words.iter()
1124 /// .map(|s| s.chars())
1127 /// assert_eq!(merged, "alphabetagamma");
1130 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1131 /// in this case since it conveys intent more clearly:
1134 /// let words = ["alpha", "beta", "gamma"];
1136 /// // chars() returns an iterator
1137 /// let merged: String = words.iter()
1138 /// .flat_map(|s| s.chars())
1140 /// assert_eq!(merged, "alphabetagamma");
1143 /// Flattening once only removes one level of nesting:
1146 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1148 /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1149 /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1151 /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1152 /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1155 /// Here we see that `flatten()` does not perform a "deep" flatten.
1156 /// Instead, only one level of nesting is removed. That is, if you
1157 /// `flatten()` a three-dimensional array the result will be
1158 /// two-dimensional and not one-dimensional. To get a one-dimensional
1159 /// structure, you have to `flatten()` again.
1161 /// [`flat_map()`]: #method.flat_map
1163 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1164 fn flatten(self) -> Flatten<Self>
1165 where Self: Sized, Self::Item: IntoIterator {
1169 /// Creates an iterator which ends after the first [`None`].
1171 /// After an iterator returns [`None`], future calls may or may not yield
1172 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1173 /// [`None`] is given, it will always return [`None`] forever.
1175 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1176 /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1183 /// // an iterator which alternates between Some and None
1184 /// struct Alternate {
1188 /// impl Iterator for Alternate {
1189 /// type Item = i32;
1191 /// fn next(&mut self) -> Option<i32> {
1192 /// let val = self.state;
1193 /// self.state = self.state + 1;
1195 /// // if it's even, Some(i32), else None
1196 /// if val % 2 == 0 {
1204 /// let mut iter = Alternate { state: 0 };
1206 /// // we can see our iterator going back and forth
1207 /// assert_eq!(iter.next(), Some(0));
1208 /// assert_eq!(iter.next(), None);
1209 /// assert_eq!(iter.next(), Some(2));
1210 /// assert_eq!(iter.next(), None);
1212 /// // however, once we fuse it...
1213 /// let mut iter = iter.fuse();
1215 /// assert_eq!(iter.next(), Some(4));
1216 /// assert_eq!(iter.next(), None);
1218 /// // it will always return `None` after the first time.
1219 /// assert_eq!(iter.next(), None);
1220 /// assert_eq!(iter.next(), None);
1221 /// assert_eq!(iter.next(), None);
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 fn fuse(self) -> Fuse<Self> where Self: Sized {
1229 /// Do something with each element of an iterator, passing the value on.
1231 /// When using iterators, you'll often chain several of them together.
1232 /// While working on such code, you might want to check out what's
1233 /// happening at various parts in the pipeline. To do that, insert
1234 /// a call to `inspect()`.
1236 /// It's more common for `inspect()` to be used as a debugging tool than to
1237 /// exist in your final code, but applications may find it useful in certain
1238 /// situations when errors need to be logged before being discarded.
1245 /// let a = [1, 4, 2, 3];
1247 /// // this iterator sequence is complex.
1248 /// let sum = a.iter()
1250 /// .filter(|x| x % 2 == 0)
1251 /// .fold(0, |sum, i| sum + i);
1253 /// println!("{}", sum);
1255 /// // let's add some inspect() calls to investigate what's happening
1256 /// let sum = a.iter()
1258 /// .inspect(|x| println!("about to filter: {}", x))
1259 /// .filter(|x| x % 2 == 0)
1260 /// .inspect(|x| println!("made it through filter: {}", x))
1261 /// .fold(0, |sum, i| sum + i);
1263 /// println!("{}", sum);
1266 /// This will print:
1270 /// about to filter: 1
1271 /// about to filter: 4
1272 /// made it through filter: 4
1273 /// about to filter: 2
1274 /// made it through filter: 2
1275 /// about to filter: 3
1279 /// Logging errors before discarding them:
1282 /// let lines = ["1", "2", "a"];
1284 /// let sum: i32 = lines
1286 /// .map(|line| line.parse::<i32>())
1287 /// .inspect(|num| {
1288 /// if let Err(ref e) = *num {
1289 /// println!("Parsing error: {}", e);
1292 /// .filter_map(Result::ok)
1295 /// println!("Sum: {}", sum);
1298 /// This will print:
1301 /// Parsing error: invalid digit found in string
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1307 Self: Sized, F: FnMut(&Self::Item),
1309 Inspect::new(self, f)
1312 /// Borrows an iterator, rather than consuming it.
1314 /// This is useful to allow applying iterator adaptors while still
1315 /// retaining ownership of the original iterator.
1322 /// let a = [1, 2, 3];
1324 /// let iter = a.into_iter();
1326 /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1328 /// assert_eq!(sum, 6);
1330 /// // if we try to use iter again, it won't work. The following line
1331 /// // gives "error: use of moved value: `iter`
1332 /// // assert_eq!(iter.next(), None);
1334 /// // let's try that again
1335 /// let a = [1, 2, 3];
1337 /// let mut iter = a.into_iter();
1339 /// // instead, we add in a .by_ref()
1340 /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1342 /// assert_eq!(sum, 3);
1344 /// // now this is just fine:
1345 /// assert_eq!(iter.next(), Some(&3));
1346 /// assert_eq!(iter.next(), None);
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1351 /// Transforms an iterator into a collection.
1353 /// `collect()` can take anything iterable, and turn it into a relevant
1354 /// collection. This is one of the more powerful methods in the standard
1355 /// library, used in a variety of contexts.
1357 /// The most basic pattern in which `collect()` is used is to turn one
1358 /// collection into another. You take a collection, call [`iter`] on it,
1359 /// do a bunch of transformations, and then `collect()` at the end.
1361 /// One of the keys to `collect()`'s power is that many things you might
1362 /// not think of as 'collections' actually are. For example, a [`String`]
1363 /// is a collection of [`char`]s. And a collection of
1364 /// [`Result<T, E>`][`Result`] can be thought of as single
1365 /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1367 /// Because `collect()` is so general, it can cause problems with type
1368 /// inference. As such, `collect()` is one of the few times you'll see
1369 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1370 /// helps the inference algorithm understand specifically which collection
1371 /// you're trying to collect into.
1378 /// let a = [1, 2, 3];
1380 /// let doubled: Vec<i32> = a.iter()
1381 /// .map(|&x| x * 2)
1384 /// assert_eq!(vec![2, 4, 6], doubled);
1387 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1388 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1390 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1393 /// use std::collections::VecDeque;
1395 /// let a = [1, 2, 3];
1397 /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1399 /// assert_eq!(2, doubled[0]);
1400 /// assert_eq!(4, doubled[1]);
1401 /// assert_eq!(6, doubled[2]);
1404 /// Using the 'turbofish' instead of annotating `doubled`:
1407 /// let a = [1, 2, 3];
1409 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1411 /// assert_eq!(vec![2, 4, 6], doubled);
1414 /// Because `collect()` only cares about what you're collecting into, you can
1415 /// still use a partial type hint, `_`, with the turbofish:
1418 /// let a = [1, 2, 3];
1420 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1422 /// assert_eq!(vec![2, 4, 6], doubled);
1425 /// Using `collect()` to make a [`String`]:
1428 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1430 /// let hello: String = chars.iter()
1431 /// .map(|&x| x as u8)
1432 /// .map(|x| (x + 1) as char)
1435 /// assert_eq!("hello", hello);
1438 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1439 /// see if any of them failed:
1442 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1444 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1446 /// // gives us the first error
1447 /// assert_eq!(Err("nope"), result);
1449 /// let results = [Ok(1), Ok(3)];
1451 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1453 /// // gives us the list of answers
1454 /// assert_eq!(Ok(vec![1, 3]), result);
1457 /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1458 /// [`String`]: ../../std/string/struct.String.html
1459 /// [`char`]: ../../std/primitive.char.html
1460 /// [`Result`]: ../../std/result/enum.Result.html
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1464 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1465 FromIterator::from_iter(self)
1468 /// Consumes an iterator, creating two collections from it.
1470 /// The predicate passed to `partition()` can return `true`, or `false`.
1471 /// `partition()` returns a pair, all of the elements for which it returned
1472 /// `true`, and all of the elements for which it returned `false`.
1479 /// let a = [1, 2, 3];
1481 /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1483 /// .partition(|&n| n % 2 == 0);
1485 /// assert_eq!(even, vec![2]);
1486 /// assert_eq!(odd, vec![1, 3]);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn partition<B, F>(self, mut f: F) -> (B, B) where
1491 B: Default + Extend<Self::Item>,
1492 F: FnMut(&Self::Item) -> bool
1494 let mut left: B = Default::default();
1495 let mut right: B = Default::default();
1499 left.extend(Some(x))
1501 right.extend(Some(x))
1508 /// An iterator method that applies a function as long as it returns
1509 /// successfully, producing a single, final value.
1511 /// `try_fold()` takes two arguments: an initial value, and a closure with
1512 /// two arguments: an 'accumulator', and an element. The closure either
1513 /// returns successfully, with the value that the accumulator should have
1514 /// for the next iteration, or it returns failure, with an error value that
1515 /// is propagated back to the caller immediately (short-circuiting).
1517 /// The initial value is the value the accumulator will have on the first
1518 /// call. If applying the closure succeeded against every element of the
1519 /// iterator, `try_fold()` returns the final accumulator as success.
1521 /// Folding is useful whenever you have a collection of something, and want
1522 /// to produce a single value from it.
1524 /// # Note to Implementors
1526 /// Most of the other (forward) methods have default implementations in
1527 /// terms of this one, so try to implement this explicitly if it can
1528 /// do something better than the default `for` loop implementation.
1530 /// In particular, try to have this call `try_fold()` on the internal parts
1531 /// from which this iterator is composed. If multiple calls are needed,
1532 /// the `?` operator may be convenient for chaining the accumulator value
1533 /// along, but beware any invariants that need to be upheld before those
1534 /// early returns. This is a `&mut self` method, so iteration needs to be
1535 /// resumable after hitting an error here.
1542 /// let a = [1, 2, 3];
1544 /// // the checked sum of all of the elements of the array
1545 /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1547 /// assert_eq!(sum, Some(6));
1550 /// Short-circuiting:
1553 /// let a = [10, 20, 30, 100, 40, 50];
1554 /// let mut it = a.iter();
1556 /// // This sum overflows when adding the 100 element
1557 /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1558 /// assert_eq!(sum, None);
1560 /// // Because it short-circuited, the remaining elements are still
1561 /// // available through the iterator.
1562 /// assert_eq!(it.len(), 2);
1563 /// assert_eq!(it.next(), Some(&40));
1566 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1567 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1568 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1570 let mut accum = init;
1571 while let Some(x) = self.next() {
1572 accum = f(accum, x)?;
1577 /// An iterator method that applies a fallible function to each item in the
1578 /// iterator, stopping at the first error and returning that error.
1580 /// This can also be thought of as the fallible form of [`for_each()`]
1581 /// or as the stateless version of [`try_fold()`].
1583 /// [`for_each()`]: #method.for_each
1584 /// [`try_fold()`]: #method.try_fold
1589 /// use std::fs::rename;
1590 /// use std::io::{stdout, Write};
1591 /// use std::path::Path;
1593 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1595 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1596 /// assert!(res.is_ok());
1598 /// let mut it = data.iter().cloned();
1599 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1600 /// assert!(res.is_err());
1601 /// // It short-circuited, so the remaining items are still in the iterator:
1602 /// assert_eq!(it.next(), Some("stale_bread.json"));
1605 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1606 fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1607 Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1609 self.try_fold((), move |(), x| f(x))
1612 /// An iterator method that applies a function, producing a single, final value.
1614 /// `fold()` takes two arguments: an initial value, and a closure with two
1615 /// arguments: an 'accumulator', and an element. The closure returns the value that
1616 /// the accumulator should have for the next iteration.
1618 /// The initial value is the value the accumulator will have on the first
1621 /// After applying this closure to every element of the iterator, `fold()`
1622 /// returns the accumulator.
1624 /// This operation is sometimes called 'reduce' or 'inject'.
1626 /// Folding is useful whenever you have a collection of something, and want
1627 /// to produce a single value from it.
1629 /// Note: `fold()`, and similar methods that traverse the entire iterator,
1630 /// may not terminate for infinite iterators, even on traits for which a
1631 /// result is determinable in finite time.
1638 /// let a = [1, 2, 3];
1640 /// // the sum of all of the elements of the array
1641 /// let sum = a.iter().fold(0, |acc, x| acc + x);
1643 /// assert_eq!(sum, 6);
1646 /// Let's walk through each step of the iteration here:
1648 /// | element | acc | x | result |
1649 /// |---------|-----|---|--------|
1651 /// | 1 | 0 | 1 | 1 |
1652 /// | 2 | 1 | 2 | 3 |
1653 /// | 3 | 3 | 3 | 6 |
1655 /// And so, our final result, `6`.
1657 /// It's common for people who haven't used iterators a lot to
1658 /// use a `for` loop with a list of things to build up a result. Those
1659 /// can be turned into `fold()`s:
1661 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1664 /// let numbers = [1, 2, 3, 4, 5];
1666 /// let mut result = 0;
1669 /// for i in &numbers {
1670 /// result = result + i;
1674 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1676 /// // they're the same
1677 /// assert_eq!(result, result2);
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1682 Self: Sized, F: FnMut(B, Self::Item) -> B,
1684 self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1687 /// Tests if every element of the iterator matches a predicate.
1689 /// `all()` takes a closure that returns `true` or `false`. It applies
1690 /// this closure to each element of the iterator, and if they all return
1691 /// `true`, then so does `all()`. If any of them return `false`, it
1692 /// returns `false`.
1694 /// `all()` is short-circuiting; in other words, it will stop processing
1695 /// as soon as it finds a `false`, given that no matter what else happens,
1696 /// the result will also be `false`.
1698 /// An empty iterator returns `true`.
1705 /// let a = [1, 2, 3];
1707 /// assert!(a.iter().all(|&x| x > 0));
1709 /// assert!(!a.iter().all(|&x| x > 2));
1712 /// Stopping at the first `false`:
1715 /// let a = [1, 2, 3];
1717 /// let mut iter = a.iter();
1719 /// assert!(!iter.all(|&x| x != 2));
1721 /// // we can still use `iter`, as there are more elements.
1722 /// assert_eq!(iter.next(), Some(&3));
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 fn all<F>(&mut self, mut f: F) -> bool where
1727 Self: Sized, F: FnMut(Self::Item) -> bool
1729 self.try_for_each(move |x| {
1730 if f(x) { LoopState::Continue(()) }
1731 else { LoopState::Break(()) }
1732 }) == LoopState::Continue(())
1735 /// Tests if any element of the iterator matches a predicate.
1737 /// `any()` takes a closure that returns `true` or `false`. It applies
1738 /// this closure to each element of the iterator, and if any of them return
1739 /// `true`, then so does `any()`. If they all return `false`, it
1740 /// returns `false`.
1742 /// `any()` is short-circuiting; in other words, it will stop processing
1743 /// as soon as it finds a `true`, given that no matter what else happens,
1744 /// the result will also be `true`.
1746 /// An empty iterator returns `false`.
1753 /// let a = [1, 2, 3];
1755 /// assert!(a.iter().any(|&x| x > 0));
1757 /// assert!(!a.iter().any(|&x| x > 5));
1760 /// Stopping at the first `true`:
1763 /// let a = [1, 2, 3];
1765 /// let mut iter = a.iter();
1767 /// assert!(iter.any(|&x| x != 2));
1769 /// // we can still use `iter`, as there are more elements.
1770 /// assert_eq!(iter.next(), Some(&2));
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 fn any<F>(&mut self, mut f: F) -> bool where
1776 F: FnMut(Self::Item) -> bool
1778 self.try_for_each(move |x| {
1779 if f(x) { LoopState::Break(()) }
1780 else { LoopState::Continue(()) }
1781 }) == LoopState::Break(())
1784 /// Searches for an element of an iterator that satisfies a predicate.
1786 /// `find()` takes a closure that returns `true` or `false`. It applies
1787 /// this closure to each element of the iterator, and if any of them return
1788 /// `true`, then `find()` returns [`Some(element)`]. If they all return
1789 /// `false`, it returns [`None`].
1791 /// `find()` is short-circuiting; in other words, it will stop processing
1792 /// as soon as the closure returns `true`.
1794 /// Because `find()` takes a reference, and many iterators iterate over
1795 /// references, this leads to a possibly confusing situation where the
1796 /// argument is a double reference. You can see this effect in the
1797 /// examples below, with `&&x`.
1799 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1800 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1807 /// let a = [1, 2, 3];
1809 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1811 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1814 /// Stopping at the first `true`:
1817 /// let a = [1, 2, 3];
1819 /// let mut iter = a.iter();
1821 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1823 /// // we can still use `iter`, as there are more elements.
1824 /// assert_eq!(iter.next(), Some(&3));
1827 #[stable(feature = "rust1", since = "1.0.0")]
1828 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1830 P: FnMut(&Self::Item) -> bool,
1832 self.try_for_each(move |x| {
1833 if predicate(&x) { LoopState::Break(x) }
1834 else { LoopState::Continue(()) }
1838 /// Applies function to the elements of iterator and returns
1839 /// the first non-none result.
1841 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1847 /// let a = ["lol", "NaN", "2", "5"];
1849 /// let first_number = a.iter().find_map(|s| s.parse().ok());
1851 /// assert_eq!(first_number, Some(2));
1854 #[stable(feature = "iterator_find_map", since = "1.30.0")]
1855 fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1857 F: FnMut(Self::Item) -> Option<B>,
1859 self.try_for_each(move |x| {
1861 Some(x) => LoopState::Break(x),
1862 None => LoopState::Continue(()),
1867 /// Searches for an element in an iterator, returning its index.
1869 /// `position()` takes a closure that returns `true` or `false`. It applies
1870 /// this closure to each element of the iterator, and if one of them
1871 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1872 /// them return `false`, it returns [`None`].
1874 /// `position()` is short-circuiting; in other words, it will stop
1875 /// processing as soon as it finds a `true`.
1877 /// # Overflow Behavior
1879 /// The method does no guarding against overflows, so if there are more
1880 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1881 /// result or panics. If debug assertions are enabled, a panic is
1886 /// This function might panic if the iterator has more than `usize::MAX`
1887 /// non-matching elements.
1889 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1890 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1891 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1898 /// let a = [1, 2, 3];
1900 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1902 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1905 /// Stopping at the first `true`:
1908 /// let a = [1, 2, 3, 4];
1910 /// let mut iter = a.iter();
1912 /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1914 /// // we can still use `iter`, as there are more elements.
1915 /// assert_eq!(iter.next(), Some(&3));
1917 /// // The returned index depends on iterator state
1918 /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1922 #[rustc_inherit_overflow_checks]
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1926 P: FnMut(Self::Item) -> bool,
1928 // The addition might panic on overflow
1929 self.try_fold(0, move |i, x| {
1930 if predicate(x) { LoopState::Break(i) }
1931 else { LoopState::Continue(i + 1) }
1935 /// Searches for an element in an iterator from the right, returning its
1938 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1939 /// this closure to each element of the iterator, starting from the end,
1940 /// and if one of them returns `true`, then `rposition()` returns
1941 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1943 /// `rposition()` is short-circuiting; in other words, it will stop
1944 /// processing as soon as it finds a `true`.
1946 /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1947 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1954 /// let a = [1, 2, 3];
1956 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1958 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1961 /// Stopping at the first `true`:
1964 /// let a = [1, 2, 3];
1966 /// let mut iter = a.iter();
1968 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1970 /// // we can still use `iter`, as there are more elements.
1971 /// assert_eq!(iter.next(), Some(&1));
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1976 P: FnMut(Self::Item) -> bool,
1977 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1979 // No need for an overflow check here, because `ExactSizeIterator`
1980 // implies that the number of elements fits into a `usize`.
1982 self.try_rfold(n, move |i, x| {
1984 if predicate(x) { LoopState::Break(i) }
1985 else { LoopState::Continue(i) }
1989 /// Returns the maximum element of an iterator.
1991 /// If several elements are equally maximum, the last element is
1992 /// returned. If the iterator is empty, [`None`] is returned.
1994 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2001 /// let a = [1, 2, 3];
2002 /// let b: Vec<u32> = Vec::new();
2004 /// assert_eq!(a.iter().max(), Some(&3));
2005 /// assert_eq!(b.iter().max(), None);
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2011 self.max_by(Ord::cmp)
2014 /// Returns the minimum element of an iterator.
2016 /// If several elements are equally minimum, the first element is
2017 /// returned. If the iterator is empty, [`None`] is returned.
2019 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2026 /// let a = [1, 2, 3];
2027 /// let b: Vec<u32> = Vec::new();
2029 /// assert_eq!(a.iter().min(), Some(&1));
2030 /// assert_eq!(b.iter().min(), None);
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2036 self.min_by(Ord::cmp)
2039 /// Returns the element that gives the maximum value from the
2040 /// specified function.
2042 /// If several elements are equally maximum, the last element is
2043 /// returned. If the iterator is empty, [`None`] is returned.
2045 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2050 /// let a = [-3_i32, 0, 1, 5, -10];
2051 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2054 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2055 fn max_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2056 where Self: Sized, F: FnMut(&Self::Item) -> B,
2058 // switch to y even if it is only equal, to preserve stability.
2059 select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p <= y_p).map(|(_, x)| x)
2062 /// Returns the element that gives the maximum value with respect to the
2063 /// specified comparison function.
2065 /// If several elements are equally maximum, the last element is
2066 /// returned. If the iterator is empty, [`None`] is returned.
2068 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2073 /// let a = [-3_i32, 0, 1, 5, -10];
2074 /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2077 #[stable(feature = "iter_max_by", since = "1.15.0")]
2078 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2079 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2081 // switch to y even if it is only equal, to preserve stability.
2082 select_fold1(self, |x, y| compare(x, y) != Ordering::Greater)
2085 /// Returns the element that gives the minimum value from the
2086 /// specified function.
2088 /// If several elements are equally minimum, the first element is
2089 /// returned. If the iterator is empty, [`None`] is returned.
2091 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2096 /// let a = [-3_i32, 0, 1, 5, -10];
2097 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2099 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2100 fn min_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2101 where Self: Sized, F: FnMut(&Self::Item) -> B,
2103 // only switch to y if it is strictly smaller, to preserve stability.
2104 select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p > y_p).map(|(_, x)| x)
2107 /// Returns the element that gives the minimum value with respect to the
2108 /// specified comparison function.
2110 /// If several elements are equally minimum, the first element is
2111 /// returned. If the iterator is empty, [`None`] is returned.
2113 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2118 /// let a = [-3_i32, 0, 1, 5, -10];
2119 /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2122 #[stable(feature = "iter_min_by", since = "1.15.0")]
2123 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2124 where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2126 // only switch to y if it is strictly smaller, to preserve stability.
2127 select_fold1(self, |x, y| compare(x, y) == Ordering::Greater)
2131 /// Reverses an iterator's direction.
2133 /// Usually, iterators iterate from left to right. After using `rev()`,
2134 /// an iterator will instead iterate from right to left.
2136 /// This is only possible if the iterator has an end, so `rev()` only
2137 /// works on [`DoubleEndedIterator`]s.
2139 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2144 /// let a = [1, 2, 3];
2146 /// let mut iter = a.iter().rev();
2148 /// assert_eq!(iter.next(), Some(&3));
2149 /// assert_eq!(iter.next(), Some(&2));
2150 /// assert_eq!(iter.next(), Some(&1));
2152 /// assert_eq!(iter.next(), None);
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2160 /// Converts an iterator of pairs into a pair of containers.
2162 /// `unzip()` consumes an entire iterator of pairs, producing two
2163 /// collections: one from the left elements of the pairs, and one
2164 /// from the right elements.
2166 /// This function is, in some sense, the opposite of [`zip`].
2168 /// [`zip`]: #method.zip
2175 /// let a = [(1, 2), (3, 4)];
2177 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2179 /// assert_eq!(left, [1, 3]);
2180 /// assert_eq!(right, [2, 4]);
2182 #[stable(feature = "rust1", since = "1.0.0")]
2183 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2184 FromA: Default + Extend<A>,
2185 FromB: Default + Extend<B>,
2186 Self: Sized + Iterator<Item=(A, B)>,
2188 let mut ts: FromA = Default::default();
2189 let mut us: FromB = Default::default();
2191 self.for_each(|(t, u)| {
2199 /// Creates an iterator which copies all of its elements.
2201 /// This is useful when you have an iterator over `&T`, but you need an
2202 /// iterator over `T`.
2209 /// let a = [1, 2, 3];
2211 /// let v_cloned: Vec<_> = a.iter().copied().collect();
2213 /// // copied is the same as .map(|&x| x)
2214 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2216 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2217 /// assert_eq!(v_map, vec![1, 2, 3]);
2219 #[stable(feature = "iter_copied", since = "1.36.0")]
2220 fn copied<'a, T: 'a>(self) -> Copied<Self>
2221 where Self: Sized + Iterator<Item=&'a T>, T: Copy
2226 /// Creates an iterator which [`clone`]s all of its elements.
2228 /// This is useful when you have an iterator over `&T`, but you need an
2229 /// iterator over `T`.
2231 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2238 /// let a = [1, 2, 3];
2240 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2242 /// // cloned is the same as .map(|&x| x), for integers
2243 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2245 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2246 /// assert_eq!(v_map, vec![1, 2, 3]);
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2250 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2255 /// Repeats an iterator endlessly.
2257 /// Instead of stopping at [`None`], the iterator will instead start again,
2258 /// from the beginning. After iterating again, it will start at the
2259 /// beginning again. And again. And again. Forever.
2261 /// [`None`]: ../../std/option/enum.Option.html#variant.None
2268 /// let a = [1, 2, 3];
2270 /// let mut it = a.iter().cycle();
2272 /// assert_eq!(it.next(), Some(&1));
2273 /// assert_eq!(it.next(), Some(&2));
2274 /// assert_eq!(it.next(), Some(&3));
2275 /// assert_eq!(it.next(), Some(&1));
2276 /// assert_eq!(it.next(), Some(&2));
2277 /// assert_eq!(it.next(), Some(&3));
2278 /// assert_eq!(it.next(), Some(&1));
2280 #[stable(feature = "rust1", since = "1.0.0")]
2282 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2286 /// Sums the elements of an iterator.
2288 /// Takes each element, adds them together, and returns the result.
2290 /// An empty iterator returns the zero value of the type.
2294 /// When calling `sum()` and a primitive integer type is being returned, this
2295 /// method will panic if the computation overflows and debug assertions are
2303 /// let a = [1, 2, 3];
2304 /// let sum: i32 = a.iter().sum();
2306 /// assert_eq!(sum, 6);
2308 #[stable(feature = "iter_arith", since = "1.11.0")]
2309 fn sum<S>(self) -> S
2316 /// Iterates over the entire iterator, multiplying all the elements
2318 /// An empty iterator returns the one value of the type.
2322 /// When calling `product()` and a primitive integer type is being returned,
2323 /// method will panic if the computation overflows and debug assertions are
2329 /// fn factorial(n: u32) -> u32 {
2330 /// (1..=n).product()
2332 /// assert_eq!(factorial(0), 1);
2333 /// assert_eq!(factorial(1), 1);
2334 /// assert_eq!(factorial(5), 120);
2336 #[stable(feature = "iter_arith", since = "1.11.0")]
2337 fn product<P>(self) -> P
2339 P: Product<Self::Item>,
2341 Product::product(self)
2344 /// Lexicographically compares the elements of this `Iterator` with those
2346 #[stable(feature = "iter_order", since = "1.5.0")]
2347 fn cmp<I>(mut self, other: I) -> Ordering where
2348 I: IntoIterator<Item = Self::Item>,
2352 let mut other = other.into_iter();
2355 let x = match self.next() {
2356 None => if other.next().is_none() {
2357 return Ordering::Equal
2359 return Ordering::Less
2364 let y = match other.next() {
2365 None => return Ordering::Greater,
2370 Ordering::Equal => (),
2371 non_eq => return non_eq,
2376 /// Lexicographically compares the elements of this `Iterator` with those
2378 #[stable(feature = "iter_order", since = "1.5.0")]
2379 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2381 Self::Item: PartialOrd<I::Item>,
2384 let mut other = other.into_iter();
2387 let x = match self.next() {
2388 None => if other.next().is_none() {
2389 return Some(Ordering::Equal)
2391 return Some(Ordering::Less)
2396 let y = match other.next() {
2397 None => return Some(Ordering::Greater),
2401 match x.partial_cmp(&y) {
2402 Some(Ordering::Equal) => (),
2403 non_eq => return non_eq,
2408 /// Determines if the elements of this `Iterator` are equal to those of
2410 #[stable(feature = "iter_order", since = "1.5.0")]
2411 fn eq<I>(mut self, other: I) -> bool where
2413 Self::Item: PartialEq<I::Item>,
2416 let mut other = other.into_iter();
2419 let x = match self.next() {
2420 None => return other.next().is_none(),
2424 let y = match other.next() {
2425 None => return false,
2429 if x != y { return false }
2433 /// Determines if the elements of this `Iterator` are unequal to those of
2435 #[stable(feature = "iter_order", since = "1.5.0")]
2436 fn ne<I>(self, other: I) -> bool where
2438 Self::Item: PartialEq<I::Item>,
2444 /// Determines if the elements of this `Iterator` are lexicographically
2445 /// less than those of another.
2446 #[stable(feature = "iter_order", since = "1.5.0")]
2447 fn lt<I>(self, other: I) -> bool where
2449 Self::Item: PartialOrd<I::Item>,
2452 self.partial_cmp(other) == Some(Ordering::Less)
2455 /// Determines if the elements of this `Iterator` are lexicographically
2456 /// less or equal to those of another.
2457 #[stable(feature = "iter_order", since = "1.5.0")]
2458 fn le<I>(self, other: I) -> bool where
2460 Self::Item: PartialOrd<I::Item>,
2463 match self.partial_cmp(other) {
2464 Some(Ordering::Less) | Some(Ordering::Equal) => true,
2469 /// Determines if the elements of this `Iterator` are lexicographically
2470 /// greater than those of another.
2471 #[stable(feature = "iter_order", since = "1.5.0")]
2472 fn gt<I>(self, other: I) -> bool where
2474 Self::Item: PartialOrd<I::Item>,
2477 self.partial_cmp(other) == Some(Ordering::Greater)
2480 /// Determines if the elements of this `Iterator` are lexicographically
2481 /// greater than or equal to those of another.
2482 #[stable(feature = "iter_order", since = "1.5.0")]
2483 fn ge<I>(self, other: I) -> bool where
2485 Self::Item: PartialOrd<I::Item>,
2488 match self.partial_cmp(other) {
2489 Some(Ordering::Greater) | Some(Ordering::Equal) => true,
2494 /// Checks if the elements of this iterator are sorted.
2496 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2497 /// iterator yields exactly zero or one element, `true` is returned.
2499 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2500 /// implies that this function returns `false` if any two consecutive items are not
2506 /// #![feature(is_sorted)]
2508 /// assert!([1, 2, 2, 9].iter().is_sorted());
2509 /// assert!(![1, 3, 2, 4].iter().is_sorted());
2510 /// assert!([0].iter().is_sorted());
2511 /// assert!(std::iter::empty::<i32>().is_sorted());
2512 /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
2515 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2516 fn is_sorted(self) -> bool
2519 Self::Item: PartialOrd,
2521 self.is_sorted_by(|a, b| a.partial_cmp(b))
2524 /// Checks if the elements of this iterator are sorted using the given comparator function.
2526 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2527 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2528 /// [`is_sorted`]; see its documentation for more information.
2530 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2531 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2532 fn is_sorted_by<F>(mut self, mut compare: F) -> bool
2535 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>
2537 let mut last = match self.next() {
2539 None => return true,
2542 while let Some(curr) = self.next() {
2543 if compare(&last, &curr)
2544 .map(|o| o == Ordering::Greater)
2555 /// Checks if the elements of this iterator are sorted using the given key extraction
2558 /// Instead of comparing the iterator's elements directly, this function compares the keys of
2559 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
2560 /// its documentation for more information.
2562 /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2567 /// #![feature(is_sorted)]
2569 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
2570 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
2573 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2574 fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
2577 F: FnMut(&Self::Item) -> K,
2580 self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2584 /// Select an element from an iterator based on the given "comparison"
2587 /// This is an idiosyncratic helper to try to factor out the
2588 /// commonalities of {max,min}{,_by}. In particular, this avoids
2589 /// having to implement optimizations several times.
2591 fn select_fold1<I, F>(mut it: I, mut f: F) -> Option<I::Item>
2594 F: FnMut(&I::Item, &I::Item) -> bool,
2596 // start with the first element as our selection. This avoids
2597 // having to use `Option`s inside the loop, translating to a
2598 // sizeable performance gain (6x in one case).
2599 it.next().map(|first| {
2600 it.fold(first, |sel, x| if f(&sel, &x) { x } else { sel })
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 impl<I: Iterator + ?Sized> Iterator for &mut I {
2606 type Item = I::Item;
2607 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2608 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2609 fn nth(&mut self, n: usize) -> Option<Self::Item> {