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