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