]> git.proxmox.com Git - rustc.git/blob - src/libcore/iter.rs
Imported Upstream version 1.7.0+dfsg1
[rustc.git] / src / libcore / iter.rs
1 // Copyright 2013-2014 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 //! Composable external iteration
12 //!
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
17 //!
18 //! Before explaining more, let's talk about how this module is structured:
19 //!
20 //! # Organization
21 //!
22 //! This module is largely organized by type:
23 //!
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //! exist and what you can do with them. The methods of these traits are worth
26 //! putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //! module's traits. You'll usually want to look at the method that creates
30 //! the `struct`, rather than the `struct` itself. For more detail about why,
31 //! see '[Implementing Iterator](#implementing-iterator)'.
32 //!
33 //! [Traits]: #traits
34 //! [Functions]: #functions
35 //! [Structs]: #structs
36 //!
37 //! That's it! Let's dig into iterators.
38 //!
39 //! # Iterator
40 //!
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
43 //!
44 //! ```
45 //! trait Iterator {
46 //! type Item;
47 //! fn next(&mut self) -> Option<Self::Item>;
48 //! }
49 //! ```
50 //!
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
57 //!
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
60 //! them for free.
61 //!
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
65 //!
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../option/enum.Option.html
69 //!
70 //! # The three forms of iteration
71 //!
72 //! There are three common methods which can create iterators from a collection:
73 //!
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
77 //!
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
80 //!
81 //! # Implementing Iterator
82 //!
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
87 //!
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
89 //!
90 //! ```
91 //! // First, the struct:
92 //!
93 //! /// An iterator which counts from one to five
94 //! struct Counter {
95 //! count: usize,
96 //! }
97 //!
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
101 //! impl Counter {
102 //! fn new() -> Counter {
103 //! Counter { count: 0 }
104 //! }
105 //! }
106 //!
107 //! // Then, we implement `Iterator` for our `Counter`:
108 //!
109 //! impl Iterator for Counter {
110 //! // we will be counting with usize
111 //! type Item = usize;
112 //!
113 //! // next() is the only required method
114 //! fn next(&mut self) -> Option<usize> {
115 //! // increment our count. This is why we started at zero.
116 //! self.count += 1;
117 //!
118 //! // check to see if we've finished counting or not.
119 //! if self.count < 6 {
120 //! Some(self.count)
121 //! } else {
122 //! None
123 //! }
124 //! }
125 //! }
126 //!
127 //! // And now we can use it!
128 //!
129 //! let mut counter = Counter::new();
130 //!
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
133 //!
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
136 //!
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
139 //!
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
142 //!
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
145 //! ```
146 //!
147 //! This will print `1` through `5`, each on their own line.
148 //!
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
151 //! next.
152 //!
153 //! # for Loops and IntoIterator
154 //!
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
157 //!
158 //! ```
159 //! let values = vec![1, 2, 3, 4, 5];
160 //!
161 //! for x in values {
162 //! println!("{}", x);
163 //! }
164 //! ```
165 //!
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
169 //!
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
174 //! it into:
175 //!
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
178 //!
179 //! ```
180 //! let values = vec![1, 2, 3, 4, 5];
181 //!
182 //! for x in values {
183 //! println!("{}", x);
184 //! }
185 //! ```
186 //!
187 //! Rust de-sugars this into:
188 //!
189 //! ```
190 //! let values = vec![1, 2, 3, 4, 5];
191 //! {
192 //! let result = match values.into_iter() {
193 //! mut iter => loop {
194 //! match iter.next() {
195 //! Some(x) => { println!("{}", x); },
196 //! None => break,
197 //! }
198 //! },
199 //! };
200 //! result
201 //! }
202 //! ```
203 //!
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
207 //!
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
210 //!
211 //! ```ignore
212 //! impl<I: Iterator> IntoIterator for I
213 //! ```
214 //!
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
217 //!
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //! will allow your collection to be used with the `for` loop.
221 //!
222 //! # Adapters
223 //!
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
226 //! pattern'.
227 //!
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
230 //!
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
234 //!
235 //! # Laziness
236 //!
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
242 //!
243 //! ```
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
247 //! ```
248 //!
249 //! This will not print any values, as we only created an iterator, rather than
250 //! using it. The compiler will warn us about this kind of behavior:
251 //!
252 //! ```text
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
255 //! ```
256 //!
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
259 //!
260 //! ```
261 //! let v = vec![1, 2, 3, 4, 5];
262 //!
263 //! for x in &v {
264 //! println!("{}", x);
265 //! }
266 //! ```
267 //!
268 //! [`map()`]: trait.Iterator.html#method.map
269 //!
270 //! The two most common ways to evaluate an iterator are to use a `for` loop
271 //! like this, or using the [`collect()`] adapter to produce a new collection.
272 //!
273 //! [`collect()`]: trait.Iterator.html#method.collect
274 //!
275 //! # Infinity
276 //!
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
279 //!
280 //! ```
281 //! let numbers = 0..;
282 //! ```
283 //!
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
286 //!
287 //! ```
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
290 //!
291 //! for number in five_numbers {
292 //! println!("{}", number);
293 //! }
294 //! ```
295 //!
296 //! This will print the numbers `0` through `4`, each on their own line.
297 //!
298 //! [`take()`]: trait.Iterator.html#method.take
299
300 #![stable(feature = "rust1", since = "1.0.0")]
301
302 use clone::Clone;
303 use cmp;
304 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
305 use default::Default;
306 use marker;
307 use mem;
308 use num::{Zero, One};
309 use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
310 use option::Option::{self, Some, None};
311 use marker::Sized;
312 use usize;
313
314 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
315
316 /// An interface for dealing with iterators.
317 ///
318 /// This is the main iterator trait. For more about the concept of iterators
319 /// generally, please see the [module-level documentation]. In particular, you
320 /// may want to know how to [implement `Iterator`][impl].
321 ///
322 /// [module-level documentation]: index.html
323 /// [impl]: index.html#implementing-iterator
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
326 `.iter()` or a similar method"]
327 pub trait Iterator {
328 /// The type of the elements being iterated over.
329 #[stable(feature = "rust1", since = "1.0.0")]
330 type Item;
331
332 /// Advances the iterator and returns the next value.
333 ///
334 /// Returns `None` when iteration is finished. Individual iterator
335 /// implementations may choose to resume iteration, and so calling `next()`
336 /// again may or may not eventually start returning `Some(Item)` again at some
337 /// point.
338 ///
339 /// # Examples
340 ///
341 /// Basic usage:
342 ///
343 /// ```
344 /// let a = [1, 2, 3];
345 ///
346 /// let mut iter = a.iter();
347 ///
348 /// // A call to next() returns the next value...
349 /// assert_eq!(Some(&1), iter.next());
350 /// assert_eq!(Some(&2), iter.next());
351 /// assert_eq!(Some(&3), iter.next());
352 ///
353 /// // ... and then None once it's over.
354 /// assert_eq!(None, iter.next());
355 ///
356 /// // More calls may or may not return None. Here, they always will.
357 /// assert_eq!(None, iter.next());
358 /// assert_eq!(None, iter.next());
359 /// ```
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn next(&mut self) -> Option<Self::Item>;
362
363 /// Returns the bounds on the remaining length of the iterator.
364 ///
365 /// Specifically, `size_hint()` returns a tuple where the first element
366 /// is the lower bound, and the second element is the upper bound.
367 ///
368 /// The second half of the tuple that is returned is an `Option<usize>`. A
369 /// `None` here means that either there is no known upper bound, or the
370 /// upper bound is larger than `usize`.
371 ///
372 /// # Implementation notes
373 ///
374 /// It is not enforced that an iterator implementation yields the declared
375 /// number of elements. A buggy iterator may yield less than the lower bound
376 /// or more than the upper bound of elements.
377 ///
378 /// `size_hint()` is primarily intended to be used for optimizations such as
379 /// reserving space for the elements of the iterator, but must not be
380 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
381 /// implementation of `size_hint()` should not lead to memory safety
382 /// violations.
383 ///
384 /// That said, the implementation should provide a correct estimation,
385 /// because otherwise it would be a violation of the trait's protocol.
386 ///
387 /// The default implementation returns `(0, None)` which is correct for any
388 /// iterator.
389 ///
390 /// # Examples
391 ///
392 /// Basic usage:
393 ///
394 /// ```
395 /// let a = [1, 2, 3];
396 /// let iter = a.iter();
397 ///
398 /// assert_eq!((3, Some(3)), iter.size_hint());
399 /// ```
400 ///
401 /// A more complex example:
402 ///
403 /// ```
404 /// // The even numbers from zero to ten.
405 /// let iter = (0..10).filter(|x| x % 2 == 0);
406 ///
407 /// // We might iterate from zero to ten times. Knowing that it's five
408 /// // exactly wouldn't be possible without executing filter().
409 /// assert_eq!((0, Some(10)), iter.size_hint());
410 ///
411 /// // Let's add one five more numbers with chain()
412 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
413 ///
414 /// // now both bounds are increased by five
415 /// assert_eq!((5, Some(15)), iter.size_hint());
416 /// ```
417 ///
418 /// Returning `None` for an upper bound:
419 ///
420 /// ```
421 /// // an infinite iterator has no upper bound
422 /// let iter = 0..;
423 ///
424 /// assert_eq!((0, None), iter.size_hint());
425 /// ```
426 #[inline]
427 #[stable(feature = "rust1", since = "1.0.0")]
428 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
429
430 /// Consumes the iterator, counting the number of iterations and returning it.
431 ///
432 /// This method will evaluate the iterator until its [`next()`] returns
433 /// `None`. Once `None` is encountered, `count()` returns the number of
434 /// times it called [`next()`].
435 ///
436 /// [`next()`]: #method.next
437 ///
438 /// # Overflow Behavior
439 ///
440 /// The method does no guarding against overflows, so counting elements of
441 /// an iterator with more than `usize::MAX` elements either produces the
442 /// wrong result or panics. If debug assertions are enabled, a panic is
443 /// guaranteed.
444 ///
445 /// # Panics
446 ///
447 /// This function might panic if the iterator has more than `usize::MAX`
448 /// elements.
449 ///
450 /// # Examples
451 ///
452 /// Basic usage:
453 ///
454 /// ```
455 /// let a = [1, 2, 3];
456 /// assert_eq!(a.iter().count(), 3);
457 ///
458 /// let a = [1, 2, 3, 4, 5];
459 /// assert_eq!(a.iter().count(), 5);
460 /// ```
461 #[inline]
462 #[stable(feature = "rust1", since = "1.0.0")]
463 fn count(self) -> usize where Self: Sized {
464 // Might overflow.
465 self.fold(0, |cnt, _| cnt + 1)
466 }
467
468 /// Consumes the iterator, returning the last element.
469 ///
470 /// This method will evaluate the iterator until it returns `None`. While
471 /// doing so, it keeps track of the current element. After `None` is
472 /// returned, `last()` will then return the last element it saw.
473 ///
474 /// # Examples
475 ///
476 /// Basic usage:
477 ///
478 /// ```
479 /// let a = [1, 2, 3];
480 /// assert_eq!(a.iter().last(), Some(&3));
481 ///
482 /// let a = [1, 2, 3, 4, 5];
483 /// assert_eq!(a.iter().last(), Some(&5));
484 /// ```
485 #[inline]
486 #[stable(feature = "rust1", since = "1.0.0")]
487 fn last(self) -> Option<Self::Item> where Self: Sized {
488 let mut last = None;
489 for x in self { last = Some(x); }
490 last
491 }
492
493 /// Consumes the `n` first elements of the iterator, then returns the
494 /// `next()` one.
495 ///
496 /// This method will evaluate the iterator `n` times, discarding those elements.
497 /// After it does so, it will call [`next()`] and return its value.
498 ///
499 /// [`next()`]: #method.next
500 ///
501 /// Like most indexing operations, the count starts from zero, so `nth(0)`
502 /// returns the first value, `nth(1)` the second, and so on.
503 ///
504 /// `nth()` will return `None` if `n` is larger than the length of the
505 /// iterator.
506 ///
507 /// # Examples
508 ///
509 /// Basic usage:
510 ///
511 /// ```
512 /// let a = [1, 2, 3];
513 /// assert_eq!(a.iter().nth(1), Some(&2));
514 /// ```
515 ///
516 /// Calling `nth()` multiple times doesn't rewind the iterator:
517 ///
518 /// ```
519 /// let a = [1, 2, 3];
520 ///
521 /// let mut iter = a.iter();
522 ///
523 /// assert_eq!(iter.nth(1), Some(&2));
524 /// assert_eq!(iter.nth(1), None);
525 /// ```
526 ///
527 /// Returning `None` if there are less than `n` elements:
528 ///
529 /// ```
530 /// let a = [1, 2, 3];
531 /// assert_eq!(a.iter().nth(10), None);
532 /// ```
533 #[inline]
534 #[stable(feature = "rust1", since = "1.0.0")]
535 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
536 for x in self {
537 if n == 0 { return Some(x) }
538 n -= 1;
539 }
540 None
541 }
542
543 /// Takes two iterators and creates a new iterator over both in sequence.
544 ///
545 /// `chain()` will return a new iterator which will first iterate over
546 /// values from the first iterator and then over values from the second
547 /// iterator.
548 ///
549 /// In other words, it links two iterators together, in a chain. 🔗
550 ///
551 /// # Examples
552 ///
553 /// Basic usage:
554 ///
555 /// ```
556 /// let a1 = [1, 2, 3];
557 /// let a2 = [4, 5, 6];
558 ///
559 /// let mut iter = a1.iter().chain(a2.iter());
560 ///
561 /// assert_eq!(iter.next(), Some(&1));
562 /// assert_eq!(iter.next(), Some(&2));
563 /// assert_eq!(iter.next(), Some(&3));
564 /// assert_eq!(iter.next(), Some(&4));
565 /// assert_eq!(iter.next(), Some(&5));
566 /// assert_eq!(iter.next(), Some(&6));
567 /// assert_eq!(iter.next(), None);
568 /// ```
569 ///
570 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
571 /// anything that can be converted into an [`Iterator`], not just an
572 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
573 /// [`IntoIterator`], and so can be passed to `chain()` directly:
574 ///
575 /// [`IntoIterator`]: trait.IntoIterator.html
576 /// [`Iterator`]: trait.Iterator.html
577 ///
578 /// ```
579 /// let s1 = &[1, 2, 3];
580 /// let s2 = &[4, 5, 6];
581 ///
582 /// let mut iter = s1.iter().chain(s2);
583 ///
584 /// assert_eq!(iter.next(), Some(&1));
585 /// assert_eq!(iter.next(), Some(&2));
586 /// assert_eq!(iter.next(), Some(&3));
587 /// assert_eq!(iter.next(), Some(&4));
588 /// assert_eq!(iter.next(), Some(&5));
589 /// assert_eq!(iter.next(), Some(&6));
590 /// assert_eq!(iter.next(), None);
591 /// ```
592 #[inline]
593 #[stable(feature = "rust1", since = "1.0.0")]
594 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
595 Self: Sized, U: IntoIterator<Item=Self::Item>,
596 {
597 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
598 }
599
600 /// 'Zips up' two iterators into a single iterator of pairs.
601 ///
602 /// `zip()` returns a new iterator that will iterate over two other
603 /// iterators, returning a tuple where the first element comes from the
604 /// first iterator, and the second element comes from the second iterator.
605 ///
606 /// In other words, it zips two iterators together, into a single one.
607 ///
608 /// When either iterator returns `None`, all further calls to `next()`
609 /// will return `None`.
610 ///
611 /// # Examples
612 ///
613 /// Basic usage:
614 ///
615 /// ```
616 /// let a1 = [1, 2, 3];
617 /// let a2 = [4, 5, 6];
618 ///
619 /// let mut iter = a1.iter().zip(a2.iter());
620 ///
621 /// assert_eq!(iter.next(), Some((&1, &4)));
622 /// assert_eq!(iter.next(), Some((&2, &5)));
623 /// assert_eq!(iter.next(), Some((&3, &6)));
624 /// assert_eq!(iter.next(), None);
625 /// ```
626 ///
627 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
628 /// anything that can be converted into an [`Iterator`], not just an
629 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
630 /// [`IntoIterator`], and so can be passed to `zip()` directly:
631 ///
632 /// [`IntoIterator`]: trait.IntoIterator.html
633 /// [`Iterator`]: trait.Iterator.html
634 ///
635 /// ```
636 /// let s1 = &[1, 2, 3];
637 /// let s2 = &[4, 5, 6];
638 ///
639 /// let mut iter = s1.iter().zip(s2);
640 ///
641 /// assert_eq!(iter.next(), Some((&1, &4)));
642 /// assert_eq!(iter.next(), Some((&2, &5)));
643 /// assert_eq!(iter.next(), Some((&3, &6)));
644 /// assert_eq!(iter.next(), None);
645 /// ```
646 ///
647 /// `zip()` is often used to zip an infinite iterator to a finite one.
648 /// This works because the finite iterator will eventually return `None`,
649 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
650 ///
651 /// ```
652 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
653 ///
654 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
655 ///
656 /// assert_eq!((0, 'f'), enumerate[0]);
657 /// assert_eq!((0, 'f'), zipper[0]);
658 ///
659 /// assert_eq!((1, 'o'), enumerate[1]);
660 /// assert_eq!((1, 'o'), zipper[1]);
661 ///
662 /// assert_eq!((2, 'o'), enumerate[2]);
663 /// assert_eq!((2, 'o'), zipper[2]);
664 /// ```
665 ///
666 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
667 #[inline]
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
670 Self: Sized, U: IntoIterator
671 {
672 Zip{a: self, b: other.into_iter()}
673 }
674
675 /// Takes a closure and creates an iterator which calls that closure on each
676 /// element.
677 ///
678 /// `map()` transforms one iterator into another, by means of its argument:
679 /// something that implements `FnMut`. It produces a new iterator which
680 /// calls this closure on each element of the original iterator.
681 ///
682 /// If you are good at thinking in types, you can think of `map()` like this:
683 /// If you have an iterator that gives you elements of some type `A`, and
684 /// you want an iterator of some other type `B`, you can use `map()`,
685 /// passing a closure that takes an `A` and returns a `B`.
686 ///
687 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
688 /// lazy, it is best used when you're already working with other iterators.
689 /// If you're doing some sort of looping for a side effect, it's considered
690 /// more idiomatic to use [`for`] than `map()`.
691 ///
692 /// [`for`]: ../../book/loops.html#for
693 ///
694 /// # Examples
695 ///
696 /// Basic usage:
697 ///
698 /// ```
699 /// let a = [1, 2, 3];
700 ///
701 /// let mut iter = a.into_iter().map(|x| 2 * x);
702 ///
703 /// assert_eq!(iter.next(), Some(2));
704 /// assert_eq!(iter.next(), Some(4));
705 /// assert_eq!(iter.next(), Some(6));
706 /// assert_eq!(iter.next(), None);
707 /// ```
708 ///
709 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
710 ///
711 /// ```
712 /// # #![allow(unused_must_use)]
713 /// // don't do this:
714 /// (0..5).map(|x| println!("{}", x));
715 ///
716 /// // it won't even execute, as it is lazy. Rust will warn you about this.
717 ///
718 /// // Instead, use for:
719 /// for x in 0..5 {
720 /// println!("{}", x);
721 /// }
722 /// ```
723 #[inline]
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn map<B, F>(self, f: F) -> Map<Self, F> where
726 Self: Sized, F: FnMut(Self::Item) -> B,
727 {
728 Map{iter: self, f: f}
729 }
730
731 /// Creates an iterator which uses a closure to determine if an element
732 /// should be yielded.
733 ///
734 /// The closure must return `true` or `false`. `filter()` creates an
735 /// iterator which calls this closure on each element. If the closure
736 /// returns `true`, then the element is returned. If the closure returns
737 /// `false`, it will try again, and call the closure on the next element,
738 /// seeing if it passes the test.
739 ///
740 /// # Examples
741 ///
742 /// Basic usage:
743 ///
744 /// ```
745 /// let a = [0i32, 1, 2];
746 ///
747 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
748 ///
749 /// assert_eq!(iter.next(), Some(&1));
750 /// assert_eq!(iter.next(), Some(&2));
751 /// assert_eq!(iter.next(), None);
752 /// ```
753 ///
754 /// Because the closure passed to `filter()` takes a reference, and many
755 /// iterators iterate over references, this leads to a possibly confusing
756 /// situation, where the type of the closure is a double reference:
757 ///
758 /// ```
759 /// let a = [0, 1, 2];
760 ///
761 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
762 ///
763 /// assert_eq!(iter.next(), Some(&2));
764 /// assert_eq!(iter.next(), None);
765 /// ```
766 ///
767 /// It's common to instead use destructuring on the argument to strip away
768 /// one:
769 ///
770 /// ```
771 /// let a = [0, 1, 2];
772 ///
773 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
774 ///
775 /// assert_eq!(iter.next(), Some(&2));
776 /// assert_eq!(iter.next(), None);
777 /// ```
778 ///
779 /// or both:
780 ///
781 /// ```
782 /// let a = [0, 1, 2];
783 ///
784 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
785 ///
786 /// assert_eq!(iter.next(), Some(&2));
787 /// assert_eq!(iter.next(), None);
788 /// ```
789 ///
790 /// of these layers.
791 #[inline]
792 #[stable(feature = "rust1", since = "1.0.0")]
793 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
794 Self: Sized, P: FnMut(&Self::Item) -> bool,
795 {
796 Filter{iter: self, predicate: predicate}
797 }
798
799 /// Creates an iterator that both filters and maps.
800 ///
801 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
802 /// iterator which calls this closure on each element. If the closure
803 /// returns `Some(element)`, then that element is returned. If the
804 /// closure returns `None`, it will try again, and call the closure on the
805 /// next element, seeing if it will return `Some`.
806 ///
807 /// [`Option<T>`]: ../option/enum.Option.html
808 ///
809 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
810 /// part:
811 ///
812 /// [`filter()`]: #method.filter
813 /// [`map()`]: #method.map
814 ///
815 /// > If the closure returns `Some(element)`, then that element is returned.
816 ///
817 /// In other words, it removes the [`Option<T>`] layer automatically. If your
818 /// mapping is already returning an [`Option<T>`] and you want to skip over
819 /// `None`s, then `filter_map()` is much, much nicer to use.
820 ///
821 /// # Examples
822 ///
823 /// Basic usage:
824 ///
825 /// ```
826 /// let a = ["1", "2", "lol"];
827 ///
828 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
829 ///
830 /// assert_eq!(iter.next(), Some(1));
831 /// assert_eq!(iter.next(), Some(2));
832 /// assert_eq!(iter.next(), None);
833 /// ```
834 ///
835 /// Here's the same example, but with [`filter()`] and [`map()`]:
836 ///
837 /// ```
838 /// let a = ["1", "2", "lol"];
839 ///
840 /// let mut iter = a.iter()
841 /// .map(|s| s.parse().ok())
842 /// .filter(|s| s.is_some());
843 ///
844 /// assert_eq!(iter.next(), Some(Some(1)));
845 /// assert_eq!(iter.next(), Some(Some(2)));
846 /// assert_eq!(iter.next(), None);
847 /// ```
848 ///
849 /// There's an extra layer of `Some` in there.
850 #[inline]
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
853 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
854 {
855 FilterMap { iter: self, f: f }
856 }
857
858 /// Creates an iterator which gives the current iteration count as well as
859 /// the next value.
860 ///
861 /// The iterator returned yields pairs `(i, val)`, where `i` is the
862 /// current index of iteration and `val` is the value returned by the
863 /// iterator.
864 ///
865 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
866 /// different sized integer, the [`zip()`] function provides similar
867 /// functionality.
868 ///
869 /// [`usize`]: ../primitive.usize.html
870 /// [`zip()`]: #method.zip
871 ///
872 /// # Overflow Behavior
873 ///
874 /// The method does no guarding against overflows, so enumerating more than
875 /// [`usize::MAX`] elements either produces the wrong result or panics. If
876 /// debug assertions are enabled, a panic is guaranteed.
877 ///
878 /// [`usize::MAX`]: ../usize/constant.MAX.html
879 ///
880 /// # Panics
881 ///
882 /// The returned iterator might panic if the to-be-returned index would
883 /// overflow a `usize`.
884 ///
885 /// # Examples
886 ///
887 /// ```
888 /// let a = [1, 2, 3];
889 ///
890 /// let mut iter = a.iter().enumerate();
891 ///
892 /// assert_eq!(iter.next(), Some((0, &1)));
893 /// assert_eq!(iter.next(), Some((1, &2)));
894 /// assert_eq!(iter.next(), Some((2, &3)));
895 /// assert_eq!(iter.next(), None);
896 /// ```
897 #[inline]
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
900 Enumerate { iter: self, count: 0 }
901 }
902
903 /// Creates an iterator which can look at the `next()` element without
904 /// consuming it.
905 ///
906 /// Adds a [`peek()`] method to an iterator. See its documentation for
907 /// more information.
908 ///
909 /// [`peek()`]: struct.Peekable.html#method.peek
910 ///
911 /// # Examples
912 ///
913 /// Basic usage:
914 ///
915 /// ```
916 /// let xs = [1, 2, 3];
917 ///
918 /// let mut iter = xs.iter().peekable();
919 ///
920 /// // peek() lets us see into the future
921 /// assert_eq!(iter.peek(), Some(&&1));
922 /// assert_eq!(iter.next(), Some(&1));
923 ///
924 /// assert_eq!(iter.next(), Some(&2));
925 ///
926 /// // we can peek() multiple times, the iterator won't advance
927 /// assert_eq!(iter.peek(), Some(&&3));
928 /// assert_eq!(iter.peek(), Some(&&3));
929 ///
930 /// assert_eq!(iter.next(), Some(&3));
931 ///
932 /// // after the iterator is finished, so is peek()
933 /// assert_eq!(iter.peek(), None);
934 /// assert_eq!(iter.next(), None);
935 /// ```
936 #[inline]
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn peekable(self) -> Peekable<Self> where Self: Sized {
939 Peekable{iter: self, peeked: None}
940 }
941
942 /// Creates an iterator that [`skip()`]s elements based on a predicate.
943 ///
944 /// [`skip()`]: #method.skip
945 ///
946 /// `skip_while()` takes a closure as an argument. It will call this
947 /// closure on each element of the iterator, and ignore elements
948 /// until it returns `false`.
949 ///
950 /// After `false` is returned, `skip_while()`'s job is over, and the
951 /// rest of the elements are yielded.
952 ///
953 /// # Examples
954 ///
955 /// Basic usage:
956 ///
957 /// ```
958 /// let a = [-1i32, 0, 1];
959 ///
960 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
961 ///
962 /// assert_eq!(iter.next(), Some(&0));
963 /// assert_eq!(iter.next(), Some(&1));
964 /// assert_eq!(iter.next(), None);
965 /// ```
966 ///
967 /// Because the closure passed to `skip_while()` takes a reference, and many
968 /// iterators iterate over references, this leads to a possibly confusing
969 /// situation, where the type of the closure is a double reference:
970 ///
971 /// ```
972 /// let a = [-1, 0, 1];
973 ///
974 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
975 ///
976 /// assert_eq!(iter.next(), Some(&0));
977 /// assert_eq!(iter.next(), Some(&1));
978 /// assert_eq!(iter.next(), None);
979 /// ```
980 ///
981 /// Stopping after an initial `false`:
982 ///
983 /// ```
984 /// let a = [-1, 0, 1, -2];
985 ///
986 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
987 ///
988 /// assert_eq!(iter.next(), Some(&0));
989 /// assert_eq!(iter.next(), Some(&1));
990 ///
991 /// // while this would have been false, since we already got a false,
992 /// // skip_while() isn't used any more
993 /// assert_eq!(iter.next(), Some(&-2));
994 ///
995 /// assert_eq!(iter.next(), None);
996 /// ```
997 #[inline]
998 #[stable(feature = "rust1", since = "1.0.0")]
999 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
1000 Self: Sized, P: FnMut(&Self::Item) -> bool,
1001 {
1002 SkipWhile{iter: self, flag: false, predicate: predicate}
1003 }
1004
1005 /// Creates an iterator that yields elements based on a predicate.
1006 ///
1007 /// `take_while()` takes a closure as an argument. It will call this
1008 /// closure on each element of the iterator, and yield elements
1009 /// while it returns `true`.
1010 ///
1011 /// After `false` is returned, `take_while()`'s job is over, and the
1012 /// rest of the elements are ignored.
1013 ///
1014 /// # Examples
1015 ///
1016 /// Basic usage:
1017 ///
1018 /// ```
1019 /// let a = [-1i32, 0, 1];
1020 ///
1021 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1022 ///
1023 /// assert_eq!(iter.next(), Some(&-1));
1024 /// assert_eq!(iter.next(), None);
1025 /// ```
1026 ///
1027 /// Because the closure passed to `take_while()` takes a reference, and many
1028 /// iterators iterate over references, this leads to a possibly confusing
1029 /// situation, where the type of the closure is a double reference:
1030 ///
1031 /// ```
1032 /// let a = [-1, 0, 1];
1033 ///
1034 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1035 ///
1036 /// assert_eq!(iter.next(), Some(&-1));
1037 /// assert_eq!(iter.next(), None);
1038 /// ```
1039 ///
1040 /// Stopping after an initial `false`:
1041 ///
1042 /// ```
1043 /// let a = [-1, 0, 1, -2];
1044 ///
1045 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1046 ///
1047 /// assert_eq!(iter.next(), Some(&-1));
1048 ///
1049 /// // We have more elements that are less than zero, but since we already
1050 /// // got a false, take_while() isn't used any more
1051 /// assert_eq!(iter.next(), None);
1052 /// ```
1053 #[inline]
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1056 Self: Sized, P: FnMut(&Self::Item) -> bool,
1057 {
1058 TakeWhile{iter: self, flag: false, predicate: predicate}
1059 }
1060
1061 /// Creates an iterator that skips the first `n` elements.
1062 ///
1063 /// After they have been consumed, the rest of the elements are yielded.
1064 ///
1065 /// # Examples
1066 ///
1067 /// Basic usage:
1068 ///
1069 /// ```
1070 /// let a = [1, 2, 3];
1071 ///
1072 /// let mut iter = a.iter().skip(2);
1073 ///
1074 /// assert_eq!(iter.next(), Some(&3));
1075 /// assert_eq!(iter.next(), None);
1076 /// ```
1077 #[inline]
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1080 Skip{iter: self, n: n}
1081 }
1082
1083 /// Creates an iterator that yields its first `n` elements.
1084 ///
1085 /// # Examples
1086 ///
1087 /// Basic usage:
1088 ///
1089 /// ```
1090 /// let a = [1, 2, 3];
1091 ///
1092 /// let mut iter = a.iter().take(2);
1093 ///
1094 /// assert_eq!(iter.next(), Some(&1));
1095 /// assert_eq!(iter.next(), Some(&2));
1096 /// assert_eq!(iter.next(), None);
1097 /// ```
1098 ///
1099 /// `take()` is often used with an infinite iterator, to make it finite:
1100 ///
1101 /// ```
1102 /// let mut iter = (0..).take(3);
1103 ///
1104 /// assert_eq!(iter.next(), Some(0));
1105 /// assert_eq!(iter.next(), Some(1));
1106 /// assert_eq!(iter.next(), Some(2));
1107 /// assert_eq!(iter.next(), None);
1108 /// ```
1109 #[inline]
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1112 Take{iter: self, n: n}
1113 }
1114
1115 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1116 /// produces a new iterator.
1117 ///
1118 /// [`fold()`]: #method.fold
1119 ///
1120 /// `scan()` takes two arguments: an initial value which seeds the internal
1121 /// state, and a closure with two arguments, the first being a mutable
1122 /// reference to the internal state and the second an iterator element.
1123 /// The closure can assign to the internal state to share state between
1124 /// iterations.
1125 ///
1126 /// On iteration, the closure will be applied to each element of the
1127 /// iterator and the return value from the closure, an [`Option`], is
1128 /// yielded by the iterator.
1129 ///
1130 /// [`Option`]: ../option/enum.Option.html
1131 ///
1132 /// # Examples
1133 ///
1134 /// Basic usage:
1135 ///
1136 /// ```
1137 /// let a = [1, 2, 3];
1138 ///
1139 /// let mut iter = a.iter().scan(1, |state, &x| {
1140 /// // each iteration, we'll multiply the state by the element
1141 /// *state = *state * x;
1142 ///
1143 /// // the value passed on to the next iteration
1144 /// Some(*state)
1145 /// });
1146 ///
1147 /// assert_eq!(iter.next(), Some(1));
1148 /// assert_eq!(iter.next(), Some(2));
1149 /// assert_eq!(iter.next(), Some(6));
1150 /// assert_eq!(iter.next(), None);
1151 /// ```
1152 #[inline]
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1155 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1156 {
1157 Scan{iter: self, f: f, state: initial_state}
1158 }
1159
1160 /// Creates an iterator that works like map, but flattens nested structure.
1161 ///
1162 /// The [`map()`] adapter is very useful, but only when the closure
1163 /// argument produces values. If it produces an iterator instead, there's
1164 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1165 /// on its own.
1166 ///
1167 /// [`map()`]: #method.map
1168 ///
1169 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1170 /// one item for each element, and `flat_map()`'s closure returns an
1171 /// iterator for each element.
1172 ///
1173 /// # Examples
1174 ///
1175 /// Basic usage:
1176 ///
1177 /// ```
1178 /// let words = ["alpha", "beta", "gamma"];
1179 ///
1180 /// // chars() returns an iterator
1181 /// let merged: String = words.iter()
1182 /// .flat_map(|s| s.chars())
1183 /// .collect();
1184 /// assert_eq!(merged, "alphabetagamma");
1185 /// ```
1186 #[inline]
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1189 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1190 {
1191 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1192 }
1193
1194 /// Creates an iterator which ends after the first `None`.
1195 ///
1196 /// After an iterator returns `None`, future calls may or may not yield
1197 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1198 /// `None` is given, it will always return `None` forever.
1199 ///
1200 /// # Examples
1201 ///
1202 /// Basic usage:
1203 ///
1204 /// ```
1205 /// // an iterator which alternates between Some and None
1206 /// struct Alternate {
1207 /// state: i32,
1208 /// }
1209 ///
1210 /// impl Iterator for Alternate {
1211 /// type Item = i32;
1212 ///
1213 /// fn next(&mut self) -> Option<i32> {
1214 /// let val = self.state;
1215 /// self.state = self.state + 1;
1216 ///
1217 /// // if it's even, Some(i32), else None
1218 /// if val % 2 == 0 {
1219 /// Some(val)
1220 /// } else {
1221 /// None
1222 /// }
1223 /// }
1224 /// }
1225 ///
1226 /// let mut iter = Alternate { state: 0 };
1227 ///
1228 /// // we can see our iterator going back and forth
1229 /// assert_eq!(iter.next(), Some(0));
1230 /// assert_eq!(iter.next(), None);
1231 /// assert_eq!(iter.next(), Some(2));
1232 /// assert_eq!(iter.next(), None);
1233 ///
1234 /// // however, once we fuse it...
1235 /// let mut iter = iter.fuse();
1236 ///
1237 /// assert_eq!(iter.next(), Some(4));
1238 /// assert_eq!(iter.next(), None);
1239 ///
1240 /// // it will always return None after the first time.
1241 /// assert_eq!(iter.next(), None);
1242 /// assert_eq!(iter.next(), None);
1243 /// assert_eq!(iter.next(), None);
1244 /// ```
1245 #[inline]
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 fn fuse(self) -> Fuse<Self> where Self: Sized {
1248 Fuse{iter: self, done: false}
1249 }
1250
1251 /// Do something with each element of an iterator, passing the value on.
1252 ///
1253 /// When using iterators, you'll often chain several of them together.
1254 /// While working on such code, you might want to check out what's
1255 /// happening at various parts in the pipeline. To do that, insert
1256 /// a call to `inspect()`.
1257 ///
1258 /// It's much more common for `inspect()` to be used as a debugging tool
1259 /// than to exist in your final code, but never say never.
1260 ///
1261 /// # Examples
1262 ///
1263 /// Basic usage:
1264 ///
1265 /// ```
1266 /// let a = [1, 4, 2, 3];
1267 ///
1268 /// // this iterator sequence is complex.
1269 /// let sum = a.iter()
1270 /// .cloned()
1271 /// .filter(|&x| x % 2 == 0)
1272 /// .fold(0, |sum, i| sum + i);
1273 ///
1274 /// println!("{}", sum);
1275 ///
1276 /// // let's add some inspect() calls to investigate what's happening
1277 /// let sum = a.iter()
1278 /// .cloned()
1279 /// .inspect(|x| println!("about to filter: {}", x))
1280 /// .filter(|&x| x % 2 == 0)
1281 /// .inspect(|x| println!("made it through filter: {}", x))
1282 /// .fold(0, |sum, i| sum + i);
1283 ///
1284 /// println!("{}", sum);
1285 /// ```
1286 ///
1287 /// This will print:
1288 ///
1289 /// ```text
1290 /// about to filter: 1
1291 /// about to filter: 4
1292 /// made it through filter: 4
1293 /// about to filter: 2
1294 /// made it through filter: 2
1295 /// about to filter: 3
1296 /// 6
1297 /// ```
1298 #[inline]
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1301 Self: Sized, F: FnMut(&Self::Item),
1302 {
1303 Inspect{iter: self, f: f}
1304 }
1305
1306 /// Borrows an iterator, rather than consuming it.
1307 ///
1308 /// This is useful to allow applying iterator adaptors while still
1309 /// retaining ownership of the original iterator.
1310 ///
1311 /// # Examples
1312 ///
1313 /// Basic usage:
1314 ///
1315 /// ```
1316 /// let a = [1, 2, 3];
1317 ///
1318 /// let iter = a.into_iter();
1319 ///
1320 /// let sum: i32 = iter.take(5)
1321 /// .fold(0, |acc, &i| acc + i );
1322 ///
1323 /// assert_eq!(sum, 6);
1324 ///
1325 /// // if we try to use iter again, it won't work. The following line
1326 /// // gives "error: use of moved value: `iter`
1327 /// // assert_eq!(iter.next(), None);
1328 ///
1329 /// // let's try that again
1330 /// let a = [1, 2, 3];
1331 ///
1332 /// let mut iter = a.into_iter();
1333 ///
1334 /// // instead, we add in a .by_ref()
1335 /// let sum: i32 = iter.by_ref()
1336 /// .take(2)
1337 /// .fold(0, |acc, &i| acc + i );
1338 ///
1339 /// assert_eq!(sum, 3);
1340 ///
1341 /// // now this is just fine:
1342 /// assert_eq!(iter.next(), Some(&3));
1343 /// assert_eq!(iter.next(), None);
1344 /// ```
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1347
1348 /// Transforms an iterator into a collection.
1349 ///
1350 /// `collect()` can take anything iterable, and turn it into a relevant
1351 /// collection. This is one of the more powerful methods in the standard
1352 /// library, used in a variety of contexts.
1353 ///
1354 /// The most basic pattern in which `collect()` is used is to turn one
1355 /// collection into another. You take a collection, call `iter()` on it,
1356 /// do a bunch of transformations, and then `collect()` at the end.
1357 ///
1358 /// One of the keys to `collect()`'s power is that many things you might
1359 /// not think of as 'collections' actually are. For example, a [`String`]
1360 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1361 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1362 /// below for more.
1363 ///
1364 /// [`String`]: ../string/struct.String.html
1365 /// [`Result<T, E>`]: ../result/enum.Result.html
1366 /// [`char`]: ../primitive.char.html
1367 ///
1368 /// Because `collect()` is so general, it can cause problems with type
1369 /// inference. As such, `collect()` is one of the few times you'll see
1370 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1371 /// helps the inference algorithm understand specifically which collection
1372 /// you're trying to collect into.
1373 ///
1374 /// # Examples
1375 ///
1376 /// Basic usage:
1377 ///
1378 /// ```
1379 /// let a = [1, 2, 3];
1380 ///
1381 /// let doubled: Vec<i32> = a.iter()
1382 /// .map(|&x| x * 2)
1383 /// .collect();
1384 ///
1385 /// assert_eq!(vec![2, 4, 6], doubled);
1386 /// ```
1387 ///
1388 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1389 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1390 ///
1391 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1392 ///
1393 /// ```
1394 /// use std::collections::VecDeque;
1395 ///
1396 /// let a = [1, 2, 3];
1397 ///
1398 /// let doubled: VecDeque<i32> = a.iter()
1399 /// .map(|&x| x * 2)
1400 /// .collect();
1401 ///
1402 /// assert_eq!(2, doubled[0]);
1403 /// assert_eq!(4, doubled[1]);
1404 /// assert_eq!(6, doubled[2]);
1405 /// ```
1406 ///
1407 /// Using the 'turbofish' instead of annotationg `doubled`:
1408 ///
1409 /// ```
1410 /// let a = [1, 2, 3];
1411 ///
1412 /// let doubled = a.iter()
1413 /// .map(|&x| x * 2)
1414 /// .collect::<Vec<i32>>();
1415 ///
1416 /// assert_eq!(vec![2, 4, 6], doubled);
1417 /// ```
1418 ///
1419 /// Because `collect()` cares about what you're collecting into, you can
1420 /// still use a partial type hint, `_`, with the turbofish:
1421 ///
1422 /// ```
1423 /// let a = [1, 2, 3];
1424 ///
1425 /// let doubled = a.iter()
1426 /// .map(|&x| x * 2)
1427 /// .collect::<Vec<_>>();
1428 ///
1429 /// assert_eq!(vec![2, 4, 6], doubled);
1430 /// ```
1431 ///
1432 /// Using `collect()` to make a [`String`]:
1433 ///
1434 /// ```
1435 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1436 ///
1437 /// let hello: String = chars.iter()
1438 /// .map(|&x| x as u8)
1439 /// .map(|x| (x + 1) as char)
1440 /// .collect();
1441 ///
1442 /// assert_eq!("hello", hello);
1443 /// ```
1444 ///
1445 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1446 /// see if any of them failed:
1447 ///
1448 /// ```
1449 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1450 ///
1451 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1452 ///
1453 /// // gives us the first error
1454 /// assert_eq!(Err("nope"), result);
1455 ///
1456 /// let results = [Ok(1), Ok(3)];
1457 ///
1458 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1459 ///
1460 /// // gives us the list of answers
1461 /// assert_eq!(Ok(vec![1, 3]), result);
1462 /// ```
1463 #[inline]
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1466 FromIterator::from_iter(self)
1467 }
1468
1469 /// Consumes an iterator, creating two collections from it.
1470 ///
1471 /// The predicate passed to `partition()` can return `true`, or `false`.
1472 /// `partition()` returns a pair, all of the elements for which it returned
1473 /// `true`, and all of the elements for which it returned `false`.
1474 ///
1475 /// # Examples
1476 ///
1477 /// Basic usage:
1478 ///
1479 /// ```
1480 /// let a = [1, 2, 3];
1481 ///
1482 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1483 /// .partition(|&n| n % 2 == 0);
1484 ///
1485 /// assert_eq!(even, vec![2]);
1486 /// assert_eq!(odd, vec![1, 3]);
1487 /// ```
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn partition<B, F>(self, mut f: F) -> (B, B) where
1490 Self: Sized,
1491 B: Default + Extend<Self::Item>,
1492 F: FnMut(&Self::Item) -> bool
1493 {
1494 let mut left: B = Default::default();
1495 let mut right: B = Default::default();
1496
1497 for x in self {
1498 if f(&x) {
1499 left.extend(Some(x))
1500 } else {
1501 right.extend(Some(x))
1502 }
1503 }
1504
1505 (left, right)
1506 }
1507
1508 /// An iterator adaptor that applies a function, producing a single, final value.
1509 ///
1510 /// `fold()` takes two arguments: an initial value, and a closure with two
1511 /// arguments: an 'accumulator', and an element. It returns the value that
1512 /// the accumulator should have for the next iteration.
1513 ///
1514 /// The initial value is the value the accumulator will have on the first
1515 /// call.
1516 ///
1517 /// After applying this closure to every element of the iterator, `fold()`
1518 /// returns the accumulator.
1519 ///
1520 /// This operation is sometimes called 'reduce' or 'inject'.
1521 ///
1522 /// Folding is useful whenever you have a collection of something, and want
1523 /// to produce a single value from it.
1524 ///
1525 /// # Examples
1526 ///
1527 /// Basic usage:
1528 ///
1529 /// ```
1530 /// let a = [1, 2, 3];
1531 ///
1532 /// // the sum of all of the elements of a
1533 /// let sum = a.iter()
1534 /// .fold(0, |acc, &x| acc + x);
1535 ///
1536 /// assert_eq!(sum, 6);
1537 /// ```
1538 ///
1539 /// Let's walk through each step of the iteration here:
1540 ///
1541 /// | element | acc | x | result |
1542 /// |---------|-----|---|--------|
1543 /// | | 0 | | |
1544 /// | 1 | 0 | 1 | 1 |
1545 /// | 2 | 1 | 2 | 3 |
1546 /// | 3 | 3 | 3 | 6 |
1547 ///
1548 /// And so, our final result, `6`.
1549 ///
1550 /// It's common for people who haven't used iterators a lot to
1551 /// use a `for` loop with a list of things to build up a result. Those
1552 /// can be turned into `fold()`s:
1553 ///
1554 /// ```
1555 /// let numbers = [1, 2, 3, 4, 5];
1556 ///
1557 /// let mut result = 0;
1558 ///
1559 /// // for loop:
1560 /// for i in &numbers {
1561 /// result = result + i;
1562 /// }
1563 ///
1564 /// // fold:
1565 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1566 ///
1567 /// // they're the same
1568 /// assert_eq!(result, result2);
1569 /// ```
1570 #[inline]
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 fn fold<B, F>(self, init: B, mut f: F) -> B where
1573 Self: Sized, F: FnMut(B, Self::Item) -> B,
1574 {
1575 let mut accum = init;
1576 for x in self {
1577 accum = f(accum, x);
1578 }
1579 accum
1580 }
1581
1582 /// Tests if every element of the iterator matches a predicate.
1583 ///
1584 /// `all()` takes a closure that returns `true` or `false`. It applies
1585 /// this closure to each element of the iterator, and if they all return
1586 /// `true`, then so does `all()`. If any of them return `false`, it
1587 /// returns `false`.
1588 ///
1589 /// `all()` is short-circuting; in other words, it will stop processing
1590 /// as soon as it finds a `false`, given that no matter what else happens,
1591 /// the result will also be `false`.
1592 ///
1593 /// An empty iterator returns `true`.
1594 ///
1595 /// # Examples
1596 ///
1597 /// Basic usage:
1598 ///
1599 /// ```
1600 /// let a = [1, 2, 3];
1601 ///
1602 /// assert!(a.iter().all(|&x| x > 0));
1603 ///
1604 /// assert!(!a.iter().all(|&x| x > 2));
1605 /// ```
1606 ///
1607 /// Stopping at the first `false`:
1608 ///
1609 /// ```
1610 /// let a = [1, 2, 3];
1611 ///
1612 /// let mut iter = a.iter();
1613 ///
1614 /// assert!(!iter.all(|&x| x != 2));
1615 ///
1616 /// // we can still use `iter`, as there are more elements.
1617 /// assert_eq!(iter.next(), Some(&3));
1618 /// ```
1619 #[inline]
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 fn all<F>(&mut self, mut f: F) -> bool where
1622 Self: Sized, F: FnMut(Self::Item) -> bool
1623 {
1624 for x in self {
1625 if !f(x) {
1626 return false;
1627 }
1628 }
1629 true
1630 }
1631
1632 /// Tests if any element of the iterator matches a predicate.
1633 ///
1634 /// `any()` takes a closure that returns `true` or `false`. It applies
1635 /// this closure to each element of the iterator, and if any of them return
1636 /// `true`, then so does `any()`. If they all return `false`, it
1637 /// returns `false`.
1638 ///
1639 /// `any()` is short-circuting; in other words, it will stop processing
1640 /// as soon as it finds a `true`, given that no matter what else happens,
1641 /// the result will also be `true`.
1642 ///
1643 /// An empty iterator returns `false`.
1644 ///
1645 /// # Examples
1646 ///
1647 /// Basic usage:
1648 ///
1649 /// ```
1650 /// let a = [1, 2, 3];
1651 ///
1652 /// assert!(a.iter().any(|&x| x > 0));
1653 ///
1654 /// assert!(!a.iter().any(|&x| x > 5));
1655 /// ```
1656 ///
1657 /// Stopping at the first `true`:
1658 ///
1659 /// ```
1660 /// let a = [1, 2, 3];
1661 ///
1662 /// let mut iter = a.iter();
1663 ///
1664 /// assert!(iter.any(|&x| x != 2));
1665 ///
1666 /// // we can still use `iter`, as there are more elements.
1667 /// assert_eq!(iter.next(), Some(&2));
1668 /// ```
1669 #[inline]
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 fn any<F>(&mut self, mut f: F) -> bool where
1672 Self: Sized,
1673 F: FnMut(Self::Item) -> bool
1674 {
1675 for x in self {
1676 if f(x) {
1677 return true;
1678 }
1679 }
1680 false
1681 }
1682
1683 /// Searches for an element of an iterator that satisfies a predicate.
1684 ///
1685 /// `find()` takes a closure that returns `true` or `false`. It applies
1686 /// this closure to each element of the iterator, and if any of them return
1687 /// `true`, then `find()` returns `Some(element)`. If they all return
1688 /// `false`, it returns `None`.
1689 ///
1690 /// `find()` is short-circuting; in other words, it will stop processing
1691 /// as soon as the closure returns `true`.
1692 ///
1693 /// Because `find()` takes a reference, and many iterators iterate over
1694 /// references, this leads to a possibly confusing situation where the
1695 /// argument is a double reference. You can see this effect in the
1696 /// examples below, with `&&x`.
1697 ///
1698 /// # Examples
1699 ///
1700 /// Basic usage:
1701 ///
1702 /// ```
1703 /// let a = [1, 2, 3];
1704 ///
1705 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1706 ///
1707 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1708 /// ```
1709 ///
1710 /// Stopping at the first `true`:
1711 ///
1712 /// ```
1713 /// let a = [1, 2, 3];
1714 ///
1715 /// let mut iter = a.iter();
1716 ///
1717 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1718 ///
1719 /// // we can still use `iter`, as there are more elements.
1720 /// assert_eq!(iter.next(), Some(&3));
1721 /// ```
1722 #[inline]
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1725 Self: Sized,
1726 P: FnMut(&Self::Item) -> bool,
1727 {
1728 for x in self {
1729 if predicate(&x) { return Some(x) }
1730 }
1731 None
1732 }
1733
1734 /// Searches for an element in an iterator, returning its index.
1735 ///
1736 /// `position()` takes a closure that returns `true` or `false`. It applies
1737 /// this closure to each element of the iterator, and if one of them
1738 /// returns `true`, then `position()` returns `Some(index)`. If all of
1739 /// them return `false`, it returns `None`.
1740 ///
1741 /// `position()` is short-circuting; in other words, it will stop
1742 /// processing as soon as it finds a `true`.
1743 ///
1744 /// # Overflow Behavior
1745 ///
1746 /// The method does no guarding against overflows, so if there are more
1747 /// than `usize::MAX` non-matching elements, it either produces the wrong
1748 /// result or panics. If debug assertions are enabled, a panic is
1749 /// guaranteed.
1750 ///
1751 /// # Panics
1752 ///
1753 /// This function might panic if the iterator has more than `usize::MAX`
1754 /// non-matching elements.
1755 ///
1756 /// # Examples
1757 ///
1758 /// Basic usage:
1759 ///
1760 /// ```
1761 /// let a = [1, 2, 3];
1762 ///
1763 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1764 ///
1765 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1766 /// ```
1767 ///
1768 /// Stopping at the first `true`:
1769 ///
1770 /// ```
1771 /// let a = [1, 2, 3];
1772 ///
1773 /// let mut iter = a.iter();
1774 ///
1775 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1776 ///
1777 /// // we can still use `iter`, as there are more elements.
1778 /// assert_eq!(iter.next(), Some(&3));
1779 /// ```
1780 #[inline]
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1783 Self: Sized,
1784 P: FnMut(Self::Item) -> bool,
1785 {
1786 // `enumerate` might overflow.
1787 for (i, x) in self.enumerate() {
1788 if predicate(x) {
1789 return Some(i);
1790 }
1791 }
1792 None
1793 }
1794
1795 /// Searches for an element in an iterator from the right, returning its
1796 /// index.
1797 ///
1798 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1799 /// this closure to each element of the iterator, starting from the end,
1800 /// and if one of them returns `true`, then `rposition()` returns
1801 /// `Some(index)`. If all of them return `false`, it returns `None`.
1802 ///
1803 /// `rposition()` is short-circuting; in other words, it will stop
1804 /// processing as soon as it finds a `true`.
1805 ///
1806 /// # Examples
1807 ///
1808 /// Basic usage:
1809 ///
1810 /// ```
1811 /// let a = [1, 2, 3];
1812 ///
1813 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1814 ///
1815 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1816 /// ```
1817 ///
1818 /// Stopping at the first `true`:
1819 ///
1820 /// ```
1821 /// let a = [1, 2, 3];
1822 ///
1823 /// let mut iter = a.iter();
1824 ///
1825 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1826 ///
1827 /// // we can still use `iter`, as there are more elements.
1828 /// assert_eq!(iter.next(), Some(&1));
1829 /// ```
1830 #[inline]
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1833 P: FnMut(Self::Item) -> bool,
1834 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1835 {
1836 let mut i = self.len();
1837
1838 while let Some(v) = self.next_back() {
1839 if predicate(v) {
1840 return Some(i - 1);
1841 }
1842 // No need for an overflow check here, because `ExactSizeIterator`
1843 // implies that the number of elements fits into a `usize`.
1844 i -= 1;
1845 }
1846 None
1847 }
1848
1849 /// Returns the maximum element of an iterator.
1850 ///
1851 /// If the two elements are equally maximum, the latest element is
1852 /// returned.
1853 ///
1854 /// # Examples
1855 ///
1856 /// Basic usage:
1857 ///
1858 /// ```
1859 /// let a = [1, 2, 3];
1860 ///
1861 /// assert_eq!(a.iter().max(), Some(&3));
1862 /// ```
1863 #[inline]
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1866 {
1867 select_fold1(self,
1868 |_| (),
1869 // switch to y even if it is only equal, to preserve
1870 // stability.
1871 |_, x, _, y| *x <= *y)
1872 .map(|(_, x)| x)
1873 }
1874
1875 /// Returns the minimum element of an iterator.
1876 ///
1877 /// If the two elements are equally minimum, the first element is
1878 /// returned.
1879 ///
1880 /// # Examples
1881 ///
1882 /// Basic usage:
1883 ///
1884 /// ```
1885 /// let a = [1, 2, 3];
1886 ///
1887 /// assert_eq!(a.iter().min(), Some(&1));
1888 /// ```
1889 #[inline]
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1892 {
1893 select_fold1(self,
1894 |_| (),
1895 // only switch to y if it is strictly smaller, to
1896 // preserve stability.
1897 |_, x, _, y| *x > *y)
1898 .map(|(_, x)| x)
1899 }
1900
1901 #[allow(missing_docs)]
1902 #[inline]
1903 #[unstable(feature = "iter_cmp",
1904 reason = "may want to produce an Ordering directly; see #15311",
1905 issue = "27724")]
1906 #[rustc_deprecated(reason = "renamed to max_by_key", since = "1.6.0")]
1907 fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1908 Self: Sized,
1909 F: FnMut(&Self::Item) -> B,
1910 {
1911 self.max_by_key(f)
1912 }
1913
1914 /// Returns the element that gives the maximum value from the
1915 /// specified function.
1916 ///
1917 /// Returns the rightmost element if the comparison determines two elements
1918 /// to be equally maximum.
1919 ///
1920 /// # Examples
1921 ///
1922 /// ```
1923 /// let a = [-3_i32, 0, 1, 5, -10];
1924 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1925 /// ```
1926 #[inline]
1927 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1928 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1929 where Self: Sized, F: FnMut(&Self::Item) -> B,
1930 {
1931 select_fold1(self,
1932 f,
1933 // switch to y even if it is only equal, to preserve
1934 // stability.
1935 |x_p, _, y_p, _| x_p <= y_p)
1936 .map(|(_, x)| x)
1937 }
1938
1939 #[inline]
1940 #[allow(missing_docs)]
1941 #[unstable(feature = "iter_cmp",
1942 reason = "may want to produce an Ordering directly; see #15311",
1943 issue = "27724")]
1944 #[rustc_deprecated(reason = "renamed to min_by_key", since = "1.6.0")]
1945 fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1946 Self: Sized,
1947 F: FnMut(&Self::Item) -> B,
1948 {
1949 self.min_by_key(f)
1950 }
1951
1952 /// Returns the element that gives the minimum value from the
1953 /// specified function.
1954 ///
1955 /// Returns the latest element if the comparison determines two elements
1956 /// to be equally minimum.
1957 ///
1958 /// # Examples
1959 ///
1960 /// ```
1961 /// let a = [-3_i32, 0, 1, 5, -10];
1962 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1963 /// ```
1964 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1965 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1966 where Self: Sized, F: FnMut(&Self::Item) -> B,
1967 {
1968 select_fold1(self,
1969 f,
1970 // only switch to y if it is strictly smaller, to
1971 // preserve stability.
1972 |x_p, _, y_p, _| x_p > y_p)
1973 .map(|(_, x)| x)
1974 }
1975
1976 /// Reverses an iterator's direction.
1977 ///
1978 /// Usually, iterators iterate from left to right. After using `rev()`,
1979 /// an iterator will instead iterate from right to left.
1980 ///
1981 /// This is only possible if the iterator has an end, so `rev()` only
1982 /// works on [`DoubleEndedIterator`]s.
1983 ///
1984 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1985 ///
1986 /// # Examples
1987 ///
1988 /// ```
1989 /// let a = [1, 2, 3];
1990 ///
1991 /// let mut iter = a.iter().rev();
1992 ///
1993 /// assert_eq!(iter.next(), Some(&3));
1994 /// assert_eq!(iter.next(), Some(&2));
1995 /// assert_eq!(iter.next(), Some(&1));
1996 ///
1997 /// assert_eq!(iter.next(), None);
1998 /// ```
1999 #[inline]
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2002 Rev{iter: self}
2003 }
2004
2005 /// Converts an iterator of pairs into a pair of containers.
2006 ///
2007 /// `unzip()` consumes an entire iterator of pairs, producing two
2008 /// collections: one from the left elements of the pairs, and one
2009 /// from the right elements.
2010 ///
2011 /// This function is, in some sense, the opposite of [`zip()`].
2012 ///
2013 /// [`zip()`]: #method.zip
2014 ///
2015 /// # Examples
2016 ///
2017 /// Basic usage:
2018 ///
2019 /// ```
2020 /// let a = [(1, 2), (3, 4)];
2021 ///
2022 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2023 ///
2024 /// assert_eq!(left, [1, 3]);
2025 /// assert_eq!(right, [2, 4]);
2026 /// ```
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2029 FromA: Default + Extend<A>,
2030 FromB: Default + Extend<B>,
2031 Self: Sized + Iterator<Item=(A, B)>,
2032 {
2033 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
2034 impl<A> Iterator for SizeHint<A> {
2035 type Item = A;
2036
2037 fn next(&mut self) -> Option<A> { None }
2038 fn size_hint(&self) -> (usize, Option<usize>) {
2039 (self.0, self.1)
2040 }
2041 }
2042
2043 let (lo, hi) = self.size_hint();
2044 let mut ts: FromA = Default::default();
2045 let mut us: FromB = Default::default();
2046
2047 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2048 us.extend(SizeHint(lo, hi, marker::PhantomData));
2049
2050 for (t, u) in self {
2051 ts.extend(Some(t));
2052 us.extend(Some(u));
2053 }
2054
2055 (ts, us)
2056 }
2057
2058 /// Creates an iterator which clone()s all of its elements.
2059 ///
2060 /// This is useful when you have an iterator over `&T`, but you need an
2061 /// iterator over `T`.
2062 ///
2063 /// # Examples
2064 ///
2065 /// Basic usage:
2066 ///
2067 /// ```
2068 /// let a = [1, 2, 3];
2069 ///
2070 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2071 ///
2072 /// // cloned is the same as .map(|&x| x), for integers
2073 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2074 ///
2075 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2076 /// assert_eq!(v_map, vec![1, 2, 3]);
2077 /// ```
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2080 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2081 {
2082 Cloned { it: self }
2083 }
2084
2085 /// Repeats an iterator endlessly.
2086 ///
2087 /// Instead of stopping at `None`, the iterator will instead start again,
2088 /// from the beginning. After iterating again, it will start at the
2089 /// beginning again. And again. And again. Forever.
2090 ///
2091 /// # Examples
2092 ///
2093 /// Basic usage:
2094 ///
2095 /// ```
2096 /// let a = [1, 2, 3];
2097 ///
2098 /// let mut it = a.iter().cycle();
2099 ///
2100 /// assert_eq!(it.next(), Some(&1));
2101 /// assert_eq!(it.next(), Some(&2));
2102 /// assert_eq!(it.next(), Some(&3));
2103 /// assert_eq!(it.next(), Some(&1));
2104 /// assert_eq!(it.next(), Some(&2));
2105 /// assert_eq!(it.next(), Some(&3));
2106 /// assert_eq!(it.next(), Some(&1));
2107 /// ```
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 #[inline]
2110 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2111 Cycle{orig: self.clone(), iter: self}
2112 }
2113
2114 /// Sums the elements of an iterator.
2115 ///
2116 /// Takes each element, adds them together, and returns the result.
2117 ///
2118 /// An empty iterator returns the zero value of the type.
2119 ///
2120 /// # Examples
2121 ///
2122 /// Basic usage:
2123 ///
2124 /// ```
2125 /// #![feature(iter_arith)]
2126 ///
2127 /// let a = [1, 2, 3];
2128 /// let sum: i32 = a.iter().sum();
2129 ///
2130 /// assert_eq!(sum, 6);
2131 /// ```
2132 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2133 issue = "27739")]
2134 fn sum<S>(self) -> S where
2135 S: Add<Self::Item, Output=S> + Zero,
2136 Self: Sized,
2137 {
2138 self.fold(Zero::zero(), |s, e| s + e)
2139 }
2140
2141 /// Iterates over the entire iterator, multiplying all the elements
2142 ///
2143 /// An empty iterator returns the one value of the type.
2144 ///
2145 /// # Examples
2146 ///
2147 /// ```
2148 /// #![feature(iter_arith)]
2149 ///
2150 /// fn factorial(n: u32) -> u32 {
2151 /// (1..).take_while(|&i| i <= n).product()
2152 /// }
2153 /// assert_eq!(factorial(0), 1);
2154 /// assert_eq!(factorial(1), 1);
2155 /// assert_eq!(factorial(5), 120);
2156 /// ```
2157 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2158 issue = "27739")]
2159 fn product<P>(self) -> P where
2160 P: Mul<Self::Item, Output=P> + One,
2161 Self: Sized,
2162 {
2163 self.fold(One::one(), |p, e| p * e)
2164 }
2165
2166 /// Lexicographically compares the elements of this `Iterator` with those
2167 /// of another.
2168 #[stable(feature = "iter_order", since = "1.5.0")]
2169 fn cmp<I>(mut self, other: I) -> Ordering where
2170 I: IntoIterator<Item = Self::Item>,
2171 Self::Item: Ord,
2172 Self: Sized,
2173 {
2174 let mut other = other.into_iter();
2175
2176 loop {
2177 match (self.next(), other.next()) {
2178 (None, None) => return Ordering::Equal,
2179 (None, _ ) => return Ordering::Less,
2180 (_ , None) => return Ordering::Greater,
2181 (Some(x), Some(y)) => match x.cmp(&y) {
2182 Ordering::Equal => (),
2183 non_eq => return non_eq,
2184 },
2185 }
2186 }
2187 }
2188
2189 /// Lexicographically compares the elements of this `Iterator` with those
2190 /// of another.
2191 #[stable(feature = "iter_order", since = "1.5.0")]
2192 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2193 I: IntoIterator,
2194 Self::Item: PartialOrd<I::Item>,
2195 Self: Sized,
2196 {
2197 let mut other = other.into_iter();
2198
2199 loop {
2200 match (self.next(), other.next()) {
2201 (None, None) => return Some(Ordering::Equal),
2202 (None, _ ) => return Some(Ordering::Less),
2203 (_ , None) => return Some(Ordering::Greater),
2204 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2205 Some(Ordering::Equal) => (),
2206 non_eq => return non_eq,
2207 },
2208 }
2209 }
2210 }
2211
2212 /// Determines if the elements of this `Iterator` are equal to those of
2213 /// another.
2214 #[stable(feature = "iter_order", since = "1.5.0")]
2215 fn eq<I>(mut self, other: I) -> bool where
2216 I: IntoIterator,
2217 Self::Item: PartialEq<I::Item>,
2218 Self: Sized,
2219 {
2220 let mut other = other.into_iter();
2221
2222 loop {
2223 match (self.next(), other.next()) {
2224 (None, None) => return true,
2225 (None, _) | (_, None) => return false,
2226 (Some(x), Some(y)) => if x != y { return false },
2227 }
2228 }
2229 }
2230
2231 /// Determines if the elements of this `Iterator` are unequal to those of
2232 /// another.
2233 #[stable(feature = "iter_order", since = "1.5.0")]
2234 fn ne<I>(mut self, other: I) -> bool where
2235 I: IntoIterator,
2236 Self::Item: PartialEq<I::Item>,
2237 Self: Sized,
2238 {
2239 let mut other = other.into_iter();
2240
2241 loop {
2242 match (self.next(), other.next()) {
2243 (None, None) => return false,
2244 (None, _) | (_, None) => return true,
2245 (Some(x), Some(y)) => if x.ne(&y) { return true },
2246 }
2247 }
2248 }
2249
2250 /// Determines if the elements of this `Iterator` are lexicographically
2251 /// less than those of another.
2252 #[stable(feature = "iter_order", since = "1.5.0")]
2253 fn lt<I>(mut self, other: I) -> bool where
2254 I: IntoIterator,
2255 Self::Item: PartialOrd<I::Item>,
2256 Self: Sized,
2257 {
2258 let mut other = other.into_iter();
2259
2260 loop {
2261 match (self.next(), other.next()) {
2262 (None, None) => return false,
2263 (None, _ ) => return true,
2264 (_ , None) => return false,
2265 (Some(x), Some(y)) => {
2266 match x.partial_cmp(&y) {
2267 Some(Ordering::Less) => return true,
2268 Some(Ordering::Equal) => {}
2269 Some(Ordering::Greater) => return false,
2270 None => return false,
2271 }
2272 },
2273 }
2274 }
2275 }
2276
2277 /// Determines if the elements of this `Iterator` are lexicographically
2278 /// less or equal to those of another.
2279 #[stable(feature = "iter_order", since = "1.5.0")]
2280 fn le<I>(mut self, other: I) -> bool where
2281 I: IntoIterator,
2282 Self::Item: PartialOrd<I::Item>,
2283 Self: Sized,
2284 {
2285 let mut other = other.into_iter();
2286
2287 loop {
2288 match (self.next(), other.next()) {
2289 (None, None) => return true,
2290 (None, _ ) => return true,
2291 (_ , None) => return false,
2292 (Some(x), Some(y)) => {
2293 match x.partial_cmp(&y) {
2294 Some(Ordering::Less) => return true,
2295 Some(Ordering::Equal) => {}
2296 Some(Ordering::Greater) => return false,
2297 None => return false,
2298 }
2299 },
2300 }
2301 }
2302 }
2303
2304 /// Determines if the elements of this `Iterator` are lexicographically
2305 /// greater than those of another.
2306 #[stable(feature = "iter_order", since = "1.5.0")]
2307 fn gt<I>(mut self, other: I) -> bool where
2308 I: IntoIterator,
2309 Self::Item: PartialOrd<I::Item>,
2310 Self: Sized,
2311 {
2312 let mut other = other.into_iter();
2313
2314 loop {
2315 match (self.next(), other.next()) {
2316 (None, None) => return false,
2317 (None, _ ) => return false,
2318 (_ , None) => return true,
2319 (Some(x), Some(y)) => {
2320 match x.partial_cmp(&y) {
2321 Some(Ordering::Less) => return false,
2322 Some(Ordering::Equal) => {}
2323 Some(Ordering::Greater) => return true,
2324 None => return false,
2325 }
2326 }
2327 }
2328 }
2329 }
2330
2331 /// Determines if the elements of this `Iterator` are lexicographically
2332 /// greater than or equal to those of another.
2333 #[stable(feature = "iter_order", since = "1.5.0")]
2334 fn ge<I>(mut self, other: I) -> bool where
2335 I: IntoIterator,
2336 Self::Item: PartialOrd<I::Item>,
2337 Self: Sized,
2338 {
2339 let mut other = other.into_iter();
2340
2341 loop {
2342 match (self.next(), other.next()) {
2343 (None, None) => return true,
2344 (None, _ ) => return false,
2345 (_ , None) => return true,
2346 (Some(x), Some(y)) => {
2347 match x.partial_cmp(&y) {
2348 Some(Ordering::Less) => return false,
2349 Some(Ordering::Equal) => {}
2350 Some(Ordering::Greater) => return true,
2351 None => return false,
2352 }
2353 },
2354 }
2355 }
2356 }
2357 }
2358
2359 /// Select an element from an iterator based on the given projection
2360 /// and "comparison" function.
2361 ///
2362 /// This is an idiosyncratic helper to try to factor out the
2363 /// commonalities of {max,min}{,_by}. In particular, this avoids
2364 /// having to implement optimizations several times.
2365 #[inline]
2366 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2367 mut f_proj: FProj,
2368 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2369 where I: Iterator,
2370 FProj: FnMut(&I::Item) -> B,
2371 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2372 {
2373 // start with the first element as our selection. This avoids
2374 // having to use `Option`s inside the loop, translating to a
2375 // sizeable performance gain (6x in one case).
2376 it.next().map(|mut sel| {
2377 let mut sel_p = f_proj(&sel);
2378
2379 for x in it {
2380 let x_p = f_proj(&x);
2381 if f_cmp(&sel_p, &sel, &x_p, &x) {
2382 sel = x;
2383 sel_p = x_p;
2384 }
2385 }
2386 (sel_p, sel)
2387 })
2388 }
2389
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2392 type Item = I::Item;
2393 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2394 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2395 }
2396
2397 /// Conversion from an `Iterator`.
2398 ///
2399 /// By implementing `FromIterator` for a type, you define how it will be
2400 /// created from an iterator. This is common for types which describe a
2401 /// collection of some kind.
2402 ///
2403 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2404 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2405 /// documentation for more examples.
2406 ///
2407 /// [`from_iter()`]: #tymethod.from_iter
2408 /// [`Iterator`]: trait.Iterator.html
2409 /// [`collect()`]: trait.Iterator.html#method.collect
2410 ///
2411 /// See also: [`IntoIterator`].
2412 ///
2413 /// [`IntoIterator`]: trait.IntoIterator.html
2414 ///
2415 /// # Examples
2416 ///
2417 /// Basic usage:
2418 ///
2419 /// ```
2420 /// use std::iter::FromIterator;
2421 ///
2422 /// let five_fives = std::iter::repeat(5).take(5);
2423 ///
2424 /// let v = Vec::from_iter(five_fives);
2425 ///
2426 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2427 /// ```
2428 ///
2429 /// Using [`collect()`] to implicitly use `FromIterator`:
2430 ///
2431 /// ```
2432 /// let five_fives = std::iter::repeat(5).take(5);
2433 ///
2434 /// let v: Vec<i32> = five_fives.collect();
2435 ///
2436 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2437 /// ```
2438 ///
2439 /// Implementing `FromIterator` for your type:
2440 ///
2441 /// ```
2442 /// use std::iter::FromIterator;
2443 ///
2444 /// // A sample collection, that's just a wrapper over Vec<T>
2445 /// #[derive(Debug)]
2446 /// struct MyCollection(Vec<i32>);
2447 ///
2448 /// // Let's give it some methods so we can create one and add things
2449 /// // to it.
2450 /// impl MyCollection {
2451 /// fn new() -> MyCollection {
2452 /// MyCollection(Vec::new())
2453 /// }
2454 ///
2455 /// fn add(&mut self, elem: i32) {
2456 /// self.0.push(elem);
2457 /// }
2458 /// }
2459 ///
2460 /// // and we'll implement FromIterator
2461 /// impl FromIterator<i32> for MyCollection {
2462 /// fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
2463 /// let mut c = MyCollection::new();
2464 ///
2465 /// for i in iterator {
2466 /// c.add(i);
2467 /// }
2468 ///
2469 /// c
2470 /// }
2471 /// }
2472 ///
2473 /// // Now we can make a new iterator...
2474 /// let iter = (0..5).into_iter();
2475 ///
2476 /// // ... and make a MyCollection out of it
2477 /// let c = MyCollection::from_iter(iter);
2478 ///
2479 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2480 ///
2481 /// // collect works too!
2482 ///
2483 /// let iter = (0..5).into_iter();
2484 /// let c: MyCollection = iter.collect();
2485 ///
2486 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2487 /// ```
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2490 built from an iterator over elements of type `{A}`"]
2491 pub trait FromIterator<A>: Sized {
2492 /// Creates a value from an iterator.
2493 ///
2494 /// See the [module-level documentation] for more.
2495 ///
2496 /// [module-level documentation]: trait.FromIterator.html
2497 ///
2498 /// # Examples
2499 ///
2500 /// Basic usage:
2501 ///
2502 /// ```
2503 /// use std::iter::FromIterator;
2504 ///
2505 /// let five_fives = std::iter::repeat(5).take(5);
2506 ///
2507 /// let v = Vec::from_iter(five_fives);
2508 ///
2509 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2510 /// ```
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2513 }
2514
2515 /// Conversion into an `Iterator`.
2516 ///
2517 /// By implementing `IntoIterator` for a type, you define how it will be
2518 /// converted to an iterator. This is common for types which describe a
2519 /// collection of some kind.
2520 ///
2521 /// One benefit of implementing `IntoIterator` is that your type will [work
2522 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2523 ///
2524 /// See also: [`FromIterator`].
2525 ///
2526 /// [`FromIterator`]: trait.FromIterator.html
2527 ///
2528 /// # Examples
2529 ///
2530 /// Basic usage:
2531 ///
2532 /// ```
2533 /// let v = vec![1, 2, 3];
2534 ///
2535 /// let mut iter = v.into_iter();
2536 ///
2537 /// let n = iter.next();
2538 /// assert_eq!(Some(1), n);
2539 ///
2540 /// let n = iter.next();
2541 /// assert_eq!(Some(2), n);
2542 ///
2543 /// let n = iter.next();
2544 /// assert_eq!(Some(3), n);
2545 ///
2546 /// let n = iter.next();
2547 /// assert_eq!(None, n);
2548 /// ```
2549 ///
2550 /// Implementing `IntoIterator` for your type:
2551 ///
2552 /// ```
2553 /// // A sample collection, that's just a wrapper over Vec<T>
2554 /// #[derive(Debug)]
2555 /// struct MyCollection(Vec<i32>);
2556 ///
2557 /// // Let's give it some methods so we can create one and add things
2558 /// // to it.
2559 /// impl MyCollection {
2560 /// fn new() -> MyCollection {
2561 /// MyCollection(Vec::new())
2562 /// }
2563 ///
2564 /// fn add(&mut self, elem: i32) {
2565 /// self.0.push(elem);
2566 /// }
2567 /// }
2568 ///
2569 /// // and we'll implement IntoIterator
2570 /// impl IntoIterator for MyCollection {
2571 /// type Item = i32;
2572 /// type IntoIter = ::std::vec::IntoIter<i32>;
2573 ///
2574 /// fn into_iter(self) -> Self::IntoIter {
2575 /// self.0.into_iter()
2576 /// }
2577 /// }
2578 ///
2579 /// // Now we can make a new collection...
2580 /// let mut c = MyCollection::new();
2581 ///
2582 /// // ... add some stuff to it ...
2583 /// c.add(0);
2584 /// c.add(1);
2585 /// c.add(2);
2586 ///
2587 /// // ... and then turn it into an Iterator:
2588 /// for (i, n) in c.into_iter().enumerate() {
2589 /// assert_eq!(i as i32, n);
2590 /// }
2591 /// ```
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 pub trait IntoIterator {
2594 /// The type of the elements being iterated over.
2595 #[stable(feature = "rust1", since = "1.0.0")]
2596 type Item;
2597
2598 /// Which kind of iterator are we turning this into?
2599 #[stable(feature = "rust1", since = "1.0.0")]
2600 type IntoIter: Iterator<Item=Self::Item>;
2601
2602 /// Creates an iterator from a value.
2603 ///
2604 /// See the [module-level documentation] for more.
2605 ///
2606 /// [module-level documentation]: trait.IntoIterator.html
2607 ///
2608 /// # Examples
2609 ///
2610 /// Basic usage:
2611 ///
2612 /// ```
2613 /// let v = vec![1, 2, 3];
2614 ///
2615 /// let mut iter = v.into_iter();
2616 ///
2617 /// let n = iter.next();
2618 /// assert_eq!(Some(1), n);
2619 ///
2620 /// let n = iter.next();
2621 /// assert_eq!(Some(2), n);
2622 ///
2623 /// let n = iter.next();
2624 /// assert_eq!(Some(3), n);
2625 ///
2626 /// let n = iter.next();
2627 /// assert_eq!(None, n);
2628 /// ```
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 fn into_iter(self) -> Self::IntoIter;
2631 }
2632
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl<I: Iterator> IntoIterator for I {
2635 type Item = I::Item;
2636 type IntoIter = I;
2637
2638 fn into_iter(self) -> I {
2639 self
2640 }
2641 }
2642
2643 /// Extend a collection with the contents of an iterator.
2644 ///
2645 /// Iterators produce a series of values, and collections can also be thought
2646 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2647 /// to extend a collection by including the contents of that iterator.
2648 ///
2649 /// # Examples
2650 ///
2651 /// Basic usage:
2652 ///
2653 /// ```
2654 /// // You can extend a String with some chars:
2655 /// let mut message = String::from("The first three letters are: ");
2656 ///
2657 /// message.extend(&['a', 'b', 'c']);
2658 ///
2659 /// assert_eq!("abc", &message[29..32]);
2660 /// ```
2661 ///
2662 /// Implementing `Extend`:
2663 ///
2664 /// ```
2665 /// // A sample collection, that's just a wrapper over Vec<T>
2666 /// #[derive(Debug)]
2667 /// struct MyCollection(Vec<i32>);
2668 ///
2669 /// // Let's give it some methods so we can create one and add things
2670 /// // to it.
2671 /// impl MyCollection {
2672 /// fn new() -> MyCollection {
2673 /// MyCollection(Vec::new())
2674 /// }
2675 ///
2676 /// fn add(&mut self, elem: i32) {
2677 /// self.0.push(elem);
2678 /// }
2679 /// }
2680 ///
2681 /// // since MyCollection has a list of i32s, we implement Extend for i32
2682 /// impl Extend<i32> for MyCollection {
2683 ///
2684 /// // This is a bit simpler with the concrete type signature: we can call
2685 /// // extend on anything which can be turned into an Iterator which gives
2686 /// // us i32s. Because we need i32s to put into MyCollection.
2687 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2688 ///
2689 /// // The implementation is very straightforward: loop through the
2690 /// // iterator, and add() each element to ourselves.
2691 /// for elem in iterable {
2692 /// self.add(elem);
2693 /// }
2694 /// }
2695 /// }
2696 ///
2697 /// let mut c = MyCollection::new();
2698 ///
2699 /// c.add(5);
2700 /// c.add(6);
2701 /// c.add(7);
2702 ///
2703 /// // let's extend our collection with three more numbers
2704 /// c.extend(vec![1, 2, 3]);
2705 ///
2706 /// // we've added these elements onto the end
2707 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2708 /// ```
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 pub trait Extend<A> {
2711 /// Extends a collection with the contents of an iterator.
2712 ///
2713 /// As this is the only method for this trait, the [trait-level] docs
2714 /// contain more details.
2715 ///
2716 /// [trait-level]: trait.Extend.html
2717 ///
2718 /// # Examples
2719 ///
2720 /// Basic usage:
2721 ///
2722 /// ```
2723 /// // You can extend a String with some chars:
2724 /// let mut message = String::from("abc");
2725 ///
2726 /// message.extend(['d', 'e', 'f'].iter());
2727 ///
2728 /// assert_eq!("abcdef", &message);
2729 /// ```
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2732 }
2733
2734 /// An iterator able to yield elements from both ends.
2735 ///
2736 /// Something that implements `DoubleEndedIterator` has one extra capability
2737 /// over something that implements [`Iterator`]: the ability to also take
2738 /// `Item`s from the back, as well as the front.
2739 ///
2740 /// It is important to note that both back and forth work on the same range,
2741 /// and do not cross: iteration is over when they meet in the middle.
2742 ///
2743 /// [`Iterator`]: trait.Iterator.html
2744 /// # Examples
2745 ///
2746 /// Basic usage:
2747 ///
2748 /// ```
2749 /// let numbers = vec![1, 2, 3];
2750 ///
2751 /// let mut iter = numbers.iter();
2752 ///
2753 /// let n = iter.next();
2754 /// assert_eq!(Some(&1), n);
2755 ///
2756 /// let n = iter.next_back();
2757 /// assert_eq!(Some(&3), n);
2758 ///
2759 /// let n = iter.next_back();
2760 /// assert_eq!(Some(&2), n);
2761 ///
2762 /// let n = iter.next();
2763 /// assert_eq!(None, n);
2764 ///
2765 /// let n = iter.next_back();
2766 /// assert_eq!(None, n);
2767 /// ```
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 pub trait DoubleEndedIterator: Iterator {
2770 /// An iterator able to yield elements from both ends.
2771 ///
2772 /// As this is the only method for this trait, the [trait-level] docs
2773 /// contain more details.
2774 ///
2775 /// [trait-level]: trait.DoubleEndedIterator.html
2776 ///
2777 /// # Examples
2778 ///
2779 /// Basic usage:
2780 ///
2781 /// ```
2782 /// let numbers = vec![1, 2, 3];
2783 ///
2784 /// let mut iter = numbers.iter();
2785 ///
2786 /// let n = iter.next();
2787 /// assert_eq!(Some(&1), n);
2788 ///
2789 /// let n = iter.next_back();
2790 /// assert_eq!(Some(&3), n);
2791 ///
2792 /// let n = iter.next_back();
2793 /// assert_eq!(Some(&2), n);
2794 ///
2795 /// let n = iter.next();
2796 /// assert_eq!(None, n);
2797 ///
2798 /// let n = iter.next_back();
2799 /// assert_eq!(None, n);
2800 /// ```
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 fn next_back(&mut self) -> Option<Self::Item>;
2803 }
2804
2805 #[stable(feature = "rust1", since = "1.0.0")]
2806 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2807 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2808 }
2809
2810 /// An iterator that knows its exact length.
2811 ///
2812 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2813 /// If an iterator knows how many times it can iterate, providing access to
2814 /// that information can be useful. For example, if you want to iterate
2815 /// backwards, a good start is to know where the end is.
2816 ///
2817 /// When implementing an `ExactSizeIterator`, You must also implement
2818 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2819 /// return the exact size of the iterator.
2820 ///
2821 /// [`Iterator`]: trait.Iterator.html
2822 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2823 ///
2824 /// The [`len()`] method has a default implementation, so you usually shouldn't
2825 /// implement it. However, you may be able to provide a more performant
2826 /// implementation than the default, so overriding it in this case makes sense.
2827 ///
2828 /// [`len()`]: #method.len
2829 ///
2830 /// # Examples
2831 ///
2832 /// Basic usage:
2833 ///
2834 /// ```
2835 /// // a finite range knows exactly how many times it will iterate
2836 /// let five = 0..5;
2837 ///
2838 /// assert_eq!(5, five.len());
2839 /// ```
2840 ///
2841 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2842 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2843 ///
2844 /// [moddocs]: index.html
2845 ///
2846 /// ```
2847 /// # struct Counter {
2848 /// # count: usize,
2849 /// # }
2850 /// # impl Counter {
2851 /// # fn new() -> Counter {
2852 /// # Counter { count: 0 }
2853 /// # }
2854 /// # }
2855 /// # impl Iterator for Counter {
2856 /// # type Item = usize;
2857 /// # fn next(&mut self) -> Option<usize> {
2858 /// # self.count += 1;
2859 /// # if self.count < 6 {
2860 /// # Some(self.count)
2861 /// # } else {
2862 /// # None
2863 /// # }
2864 /// # }
2865 /// # }
2866 /// impl ExactSizeIterator for Counter {
2867 /// // We already have the number of iterations, so we can use it directly.
2868 /// fn len(&self) -> usize {
2869 /// self.count
2870 /// }
2871 /// }
2872 ///
2873 /// // And now we can use it!
2874 ///
2875 /// let counter = Counter::new();
2876 ///
2877 /// assert_eq!(0, counter.len());
2878 /// ```
2879 #[stable(feature = "rust1", since = "1.0.0")]
2880 pub trait ExactSizeIterator: Iterator {
2881 #[inline]
2882 #[stable(feature = "rust1", since = "1.0.0")]
2883 /// Returns the exact number of times the iterator will iterate.
2884 ///
2885 /// This method has a default implementation, so you usually should not
2886 /// implement it directly. However, if you can provide a more efficient
2887 /// implementation, you can do so. See the [trait-level] docs for an
2888 /// example.
2889 ///
2890 /// This function has the same safety guarantees as the [`size_hint()`]
2891 /// function.
2892 ///
2893 /// [trait-level]: trait.ExactSizeIterator.html
2894 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2895 ///
2896 /// # Examples
2897 ///
2898 /// Basic usage:
2899 ///
2900 /// ```
2901 /// // a finite range knows exactly how many times it will iterate
2902 /// let five = 0..5;
2903 ///
2904 /// assert_eq!(5, five.len());
2905 /// ```
2906 fn len(&self) -> usize {
2907 let (lower, upper) = self.size_hint();
2908 // Note: This assertion is overly defensive, but it checks the invariant
2909 // guaranteed by the trait. If this trait were rust-internal,
2910 // we could use debug_assert!; assert_eq! will check all Rust user
2911 // implementations too.
2912 assert_eq!(upper, Some(lower));
2913 lower
2914 }
2915 }
2916
2917 #[stable(feature = "rust1", since = "1.0.0")]
2918 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2919
2920 // All adaptors that preserve the size of the wrapped iterator are fine
2921 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2922 #[stable(feature = "rust1", since = "1.0.0")]
2923 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2924 #[stable(feature = "rust1", since = "1.0.0")]
2925 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2926 F: FnMut(&I::Item),
2927 {}
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 impl<I> ExactSizeIterator for Rev<I>
2930 where I: ExactSizeIterator + DoubleEndedIterator {}
2931 #[stable(feature = "rust1", since = "1.0.0")]
2932 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2933 F: FnMut(I::Item) -> B,
2934 {}
2935 #[stable(feature = "rust1", since = "1.0.0")]
2936 impl<A, B> ExactSizeIterator for Zip<A, B>
2937 where A: ExactSizeIterator, B: ExactSizeIterator {}
2938
2939 /// An double-ended iterator with the direction inverted.
2940 ///
2941 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2942 /// documentation for more.
2943 ///
2944 /// [`rev()`]: trait.Iterator.html#method.rev
2945 /// [`Iterator`]: trait.Iterator.html
2946 #[derive(Clone)]
2947 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 pub struct Rev<T> {
2950 iter: T
2951 }
2952
2953 #[stable(feature = "rust1", since = "1.0.0")]
2954 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2955 type Item = <I as Iterator>::Item;
2956
2957 #[inline]
2958 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2959 #[inline]
2960 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2961 }
2962
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2965 #[inline]
2966 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2967 }
2968
2969 /// An iterator that clones the elements of an underlying iterator.
2970 ///
2971 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2972 /// documentation for more.
2973 ///
2974 /// [`cloned()`]: trait.Iterator.html#method.cloned
2975 /// [`Iterator`]: trait.Iterator.html
2976 #[stable(feature = "iter_cloned", since = "1.1.0")]
2977 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2978 #[derive(Clone)]
2979 pub struct Cloned<I> {
2980 it: I,
2981 }
2982
2983 #[stable(feature = "rust1", since = "1.0.0")]
2984 impl<'a, I, T: 'a> Iterator for Cloned<I>
2985 where I: Iterator<Item=&'a T>, T: Clone
2986 {
2987 type Item = T;
2988
2989 fn next(&mut self) -> Option<T> {
2990 self.it.next().cloned()
2991 }
2992
2993 fn size_hint(&self) -> (usize, Option<usize>) {
2994 self.it.size_hint()
2995 }
2996 }
2997
2998 #[stable(feature = "rust1", since = "1.0.0")]
2999 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
3000 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
3001 {
3002 fn next_back(&mut self) -> Option<T> {
3003 self.it.next_back().cloned()
3004 }
3005 }
3006
3007 #[stable(feature = "rust1", since = "1.0.0")]
3008 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
3009 where I: ExactSizeIterator<Item=&'a T>, T: Clone
3010 {}
3011
3012 /// An iterator that repeats endlessly.
3013 ///
3014 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3015 /// documentation for more.
3016 ///
3017 /// [`cycle()`]: trait.Iterator.html#method.cycle
3018 /// [`Iterator`]: trait.Iterator.html
3019 #[derive(Clone)]
3020 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3021 #[stable(feature = "rust1", since = "1.0.0")]
3022 pub struct Cycle<I> {
3023 orig: I,
3024 iter: I,
3025 }
3026
3027 #[stable(feature = "rust1", since = "1.0.0")]
3028 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
3029 type Item = <I as Iterator>::Item;
3030
3031 #[inline]
3032 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3033 match self.iter.next() {
3034 None => { self.iter = self.orig.clone(); self.iter.next() }
3035 y => y
3036 }
3037 }
3038
3039 #[inline]
3040 fn size_hint(&self) -> (usize, Option<usize>) {
3041 // the cycle iterator is either empty or infinite
3042 match self.orig.size_hint() {
3043 sz @ (0, Some(0)) => sz,
3044 (0, _) => (0, None),
3045 _ => (usize::MAX, None)
3046 }
3047 }
3048 }
3049
3050 /// An iterator that strings two iterators together.
3051 ///
3052 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3053 /// documentation for more.
3054 ///
3055 /// [`chain()`]: trait.Iterator.html#method.chain
3056 /// [`Iterator`]: trait.Iterator.html
3057 #[derive(Clone)]
3058 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3059 #[stable(feature = "rust1", since = "1.0.0")]
3060 pub struct Chain<A, B> {
3061 a: A,
3062 b: B,
3063 state: ChainState,
3064 }
3065
3066 // The iterator protocol specifies that iteration ends with the return value
3067 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3068 // further calls return. The chain adaptor must account for this since it uses
3069 // two subiterators.
3070 //
3071 // It uses three states:
3072 //
3073 // - Both: `a` and `b` are remaining
3074 // - Front: `a` remaining
3075 // - Back: `b` remaining
3076 //
3077 // The fourth state (neither iterator is remaining) only occurs after Chain has
3078 // returned None once, so we don't need to store this state.
3079 #[derive(Clone)]
3080 enum ChainState {
3081 // both front and back iterator are remaining
3082 Both,
3083 // only front is remaining
3084 Front,
3085 // only back is remaining
3086 Back,
3087 }
3088
3089 #[stable(feature = "rust1", since = "1.0.0")]
3090 impl<A, B> Iterator for Chain<A, B> where
3091 A: Iterator,
3092 B: Iterator<Item = A::Item>
3093 {
3094 type Item = A::Item;
3095
3096 #[inline]
3097 fn next(&mut self) -> Option<A::Item> {
3098 match self.state {
3099 ChainState::Both => match self.a.next() {
3100 elt @ Some(..) => elt,
3101 None => {
3102 self.state = ChainState::Back;
3103 self.b.next()
3104 }
3105 },
3106 ChainState::Front => self.a.next(),
3107 ChainState::Back => self.b.next(),
3108 }
3109 }
3110
3111 #[inline]
3112 fn count(self) -> usize {
3113 match self.state {
3114 ChainState::Both => self.a.count() + self.b.count(),
3115 ChainState::Front => self.a.count(),
3116 ChainState::Back => self.b.count(),
3117 }
3118 }
3119
3120 #[inline]
3121 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
3122 match self.state {
3123 ChainState::Both | ChainState::Front => {
3124 for x in self.a.by_ref() {
3125 if n == 0 {
3126 return Some(x)
3127 }
3128 n -= 1;
3129 }
3130 if let ChainState::Both = self.state {
3131 self.state = ChainState::Back;
3132 }
3133 }
3134 ChainState::Back => {}
3135 }
3136 if let ChainState::Back = self.state {
3137 self.b.nth(n)
3138 } else {
3139 None
3140 }
3141 }
3142
3143 #[inline]
3144 fn last(self) -> Option<A::Item> {
3145 match self.state {
3146 ChainState::Both => {
3147 // Must exhaust a before b.
3148 let a_last = self.a.last();
3149 let b_last = self.b.last();
3150 b_last.or(a_last)
3151 },
3152 ChainState::Front => self.a.last(),
3153 ChainState::Back => self.b.last()
3154 }
3155 }
3156
3157 #[inline]
3158 fn size_hint(&self) -> (usize, Option<usize>) {
3159 let (a_lower, a_upper) = self.a.size_hint();
3160 let (b_lower, b_upper) = self.b.size_hint();
3161
3162 let lower = a_lower.saturating_add(b_lower);
3163
3164 let upper = match (a_upper, b_upper) {
3165 (Some(x), Some(y)) => x.checked_add(y),
3166 _ => None
3167 };
3168
3169 (lower, upper)
3170 }
3171 }
3172
3173 #[stable(feature = "rust1", since = "1.0.0")]
3174 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3175 A: DoubleEndedIterator,
3176 B: DoubleEndedIterator<Item=A::Item>,
3177 {
3178 #[inline]
3179 fn next_back(&mut self) -> Option<A::Item> {
3180 match self.state {
3181 ChainState::Both => match self.b.next_back() {
3182 elt @ Some(..) => elt,
3183 None => {
3184 self.state = ChainState::Front;
3185 self.a.next_back()
3186 }
3187 },
3188 ChainState::Front => self.a.next_back(),
3189 ChainState::Back => self.b.next_back(),
3190 }
3191 }
3192 }
3193
3194 /// An iterator that iterates two other iterators simultaneously.
3195 ///
3196 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3197 /// documentation for more.
3198 ///
3199 /// [`zip()`]: trait.Iterator.html#method.zip
3200 /// [`Iterator`]: trait.Iterator.html
3201 #[derive(Clone)]
3202 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3203 #[stable(feature = "rust1", since = "1.0.0")]
3204 pub struct Zip<A, B> {
3205 a: A,
3206 b: B
3207 }
3208
3209 #[stable(feature = "rust1", since = "1.0.0")]
3210 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3211 {
3212 type Item = (A::Item, B::Item);
3213
3214 #[inline]
3215 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3216 self.a.next().and_then(|x| {
3217 self.b.next().and_then(|y| {
3218 Some((x, y))
3219 })
3220 })
3221 }
3222
3223 #[inline]
3224 fn size_hint(&self) -> (usize, Option<usize>) {
3225 let (a_lower, a_upper) = self.a.size_hint();
3226 let (b_lower, b_upper) = self.b.size_hint();
3227
3228 let lower = cmp::min(a_lower, b_lower);
3229
3230 let upper = match (a_upper, b_upper) {
3231 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3232 (Some(x), None) => Some(x),
3233 (None, Some(y)) => Some(y),
3234 (None, None) => None
3235 };
3236
3237 (lower, upper)
3238 }
3239 }
3240
3241 #[stable(feature = "rust1", since = "1.0.0")]
3242 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3243 A: DoubleEndedIterator + ExactSizeIterator,
3244 B: DoubleEndedIterator + ExactSizeIterator,
3245 {
3246 #[inline]
3247 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3248 let a_sz = self.a.len();
3249 let b_sz = self.b.len();
3250 if a_sz != b_sz {
3251 // Adjust a, b to equal length
3252 if a_sz > b_sz {
3253 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3254 } else {
3255 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3256 }
3257 }
3258 match (self.a.next_back(), self.b.next_back()) {
3259 (Some(x), Some(y)) => Some((x, y)),
3260 (None, None) => None,
3261 _ => unreachable!(),
3262 }
3263 }
3264 }
3265
3266 /// An iterator that maps the values of `iter` with `f`.
3267 ///
3268 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3269 /// documentation for more.
3270 ///
3271 /// [`map()`]: trait.Iterator.html#method.map
3272 /// [`Iterator`]: trait.Iterator.html
3273 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3274 #[stable(feature = "rust1", since = "1.0.0")]
3275 #[derive(Clone)]
3276 pub struct Map<I, F> {
3277 iter: I,
3278 f: F,
3279 }
3280
3281 #[stable(feature = "rust1", since = "1.0.0")]
3282 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3283 type Item = B;
3284
3285 #[inline]
3286 fn next(&mut self) -> Option<B> {
3287 self.iter.next().map(&mut self.f)
3288 }
3289
3290 #[inline]
3291 fn size_hint(&self) -> (usize, Option<usize>) {
3292 self.iter.size_hint()
3293 }
3294 }
3295
3296 #[stable(feature = "rust1", since = "1.0.0")]
3297 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3298 F: FnMut(I::Item) -> B,
3299 {
3300 #[inline]
3301 fn next_back(&mut self) -> Option<B> {
3302 self.iter.next_back().map(&mut self.f)
3303 }
3304 }
3305
3306 /// An iterator that filters the elements of `iter` with `predicate`.
3307 ///
3308 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3309 /// documentation for more.
3310 ///
3311 /// [`filter()`]: trait.Iterator.html#method.filter
3312 /// [`Iterator`]: trait.Iterator.html
3313 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3314 #[stable(feature = "rust1", since = "1.0.0")]
3315 #[derive(Clone)]
3316 pub struct Filter<I, P> {
3317 iter: I,
3318 predicate: P,
3319 }
3320
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3323 type Item = I::Item;
3324
3325 #[inline]
3326 fn next(&mut self) -> Option<I::Item> {
3327 for x in self.iter.by_ref() {
3328 if (self.predicate)(&x) {
3329 return Some(x);
3330 }
3331 }
3332 None
3333 }
3334
3335 #[inline]
3336 fn size_hint(&self) -> (usize, Option<usize>) {
3337 let (_, upper) = self.iter.size_hint();
3338 (0, upper) // can't know a lower bound, due to the predicate
3339 }
3340 }
3341
3342 #[stable(feature = "rust1", since = "1.0.0")]
3343 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3344 where P: FnMut(&I::Item) -> bool,
3345 {
3346 #[inline]
3347 fn next_back(&mut self) -> Option<I::Item> {
3348 for x in self.iter.by_ref().rev() {
3349 if (self.predicate)(&x) {
3350 return Some(x);
3351 }
3352 }
3353 None
3354 }
3355 }
3356
3357 /// An iterator that uses `f` to both filter and map elements from `iter`.
3358 ///
3359 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3360 /// documentation for more.
3361 ///
3362 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3363 /// [`Iterator`]: trait.Iterator.html
3364 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3365 #[stable(feature = "rust1", since = "1.0.0")]
3366 #[derive(Clone)]
3367 pub struct FilterMap<I, F> {
3368 iter: I,
3369 f: F,
3370 }
3371
3372 #[stable(feature = "rust1", since = "1.0.0")]
3373 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3374 where F: FnMut(I::Item) -> Option<B>,
3375 {
3376 type Item = B;
3377
3378 #[inline]
3379 fn next(&mut self) -> Option<B> {
3380 for x in self.iter.by_ref() {
3381 if let Some(y) = (self.f)(x) {
3382 return Some(y);
3383 }
3384 }
3385 None
3386 }
3387
3388 #[inline]
3389 fn size_hint(&self) -> (usize, Option<usize>) {
3390 let (_, upper) = self.iter.size_hint();
3391 (0, upper) // can't know a lower bound, due to the predicate
3392 }
3393 }
3394
3395 #[stable(feature = "rust1", since = "1.0.0")]
3396 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3397 where F: FnMut(I::Item) -> Option<B>,
3398 {
3399 #[inline]
3400 fn next_back(&mut self) -> Option<B> {
3401 for x in self.iter.by_ref().rev() {
3402 if let Some(y) = (self.f)(x) {
3403 return Some(y);
3404 }
3405 }
3406 None
3407 }
3408 }
3409
3410 /// An iterator that yields the current count and the element during iteration.
3411 ///
3412 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3413 /// documentation for more.
3414 ///
3415 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3416 /// [`Iterator`]: trait.Iterator.html
3417 #[derive(Clone)]
3418 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3419 #[stable(feature = "rust1", since = "1.0.0")]
3420 pub struct Enumerate<I> {
3421 iter: I,
3422 count: usize,
3423 }
3424
3425 #[stable(feature = "rust1", since = "1.0.0")]
3426 impl<I> Iterator for Enumerate<I> where I: Iterator {
3427 type Item = (usize, <I as Iterator>::Item);
3428
3429 /// # Overflow Behavior
3430 ///
3431 /// The method does no guarding against overflows, so enumerating more than
3432 /// `usize::MAX` elements either produces the wrong result or panics. If
3433 /// debug assertions are enabled, a panic is guaranteed.
3434 ///
3435 /// # Panics
3436 ///
3437 /// Might panic if the index of the element overflows a `usize`.
3438 #[inline]
3439 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3440 self.iter.next().map(|a| {
3441 let ret = (self.count, a);
3442 // Possible undefined overflow.
3443 self.count += 1;
3444 ret
3445 })
3446 }
3447
3448 #[inline]
3449 fn size_hint(&self) -> (usize, Option<usize>) {
3450 self.iter.size_hint()
3451 }
3452
3453 #[inline]
3454 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3455 self.iter.nth(n).map(|a| {
3456 let i = self.count + n;
3457 self.count = i + 1;
3458 (i, a)
3459 })
3460 }
3461
3462 #[inline]
3463 fn count(self) -> usize {
3464 self.iter.count()
3465 }
3466 }
3467
3468 #[stable(feature = "rust1", since = "1.0.0")]
3469 impl<I> DoubleEndedIterator for Enumerate<I> where
3470 I: ExactSizeIterator + DoubleEndedIterator
3471 {
3472 #[inline]
3473 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3474 self.iter.next_back().map(|a| {
3475 let len = self.iter.len();
3476 // Can safely add, `ExactSizeIterator` promises that the number of
3477 // elements fits into a `usize`.
3478 (self.count + len, a)
3479 })
3480 }
3481 }
3482
3483 /// An iterator with a `peek()` that returns an optional reference to the next
3484 /// element.
3485 ///
3486 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3487 /// documentation for more.
3488 ///
3489 /// [`peekable()`]: trait.Iterator.html#method.peekable
3490 /// [`Iterator`]: trait.Iterator.html
3491 #[derive(Clone)]
3492 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 pub struct Peekable<I: Iterator> {
3495 iter: I,
3496 peeked: Option<I::Item>,
3497 }
3498
3499 #[stable(feature = "rust1", since = "1.0.0")]
3500 impl<I: Iterator> Iterator for Peekable<I> {
3501 type Item = I::Item;
3502
3503 #[inline]
3504 fn next(&mut self) -> Option<I::Item> {
3505 match self.peeked {
3506 Some(_) => self.peeked.take(),
3507 None => self.iter.next(),
3508 }
3509 }
3510
3511 #[inline]
3512 fn count(self) -> usize {
3513 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3514 }
3515
3516 #[inline]
3517 fn nth(&mut self, n: usize) -> Option<I::Item> {
3518 match self.peeked {
3519 Some(_) if n == 0 => self.peeked.take(),
3520 Some(_) => {
3521 self.peeked = None;
3522 self.iter.nth(n-1)
3523 },
3524 None => self.iter.nth(n)
3525 }
3526 }
3527
3528 #[inline]
3529 fn last(self) -> Option<I::Item> {
3530 self.iter.last().or(self.peeked)
3531 }
3532
3533 #[inline]
3534 fn size_hint(&self) -> (usize, Option<usize>) {
3535 let (lo, hi) = self.iter.size_hint();
3536 if self.peeked.is_some() {
3537 let lo = lo.saturating_add(1);
3538 let hi = hi.and_then(|x| x.checked_add(1));
3539 (lo, hi)
3540 } else {
3541 (lo, hi)
3542 }
3543 }
3544 }
3545
3546 #[stable(feature = "rust1", since = "1.0.0")]
3547 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3548
3549 impl<I: Iterator> Peekable<I> {
3550 /// Returns a reference to the next() value without advancing the iterator.
3551 ///
3552 /// The `peek()` method will return the value that a call to [`next()`] would
3553 /// return, but does not advance the iterator. Like [`next()`], if there is
3554 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3555 /// will return `None`.
3556 ///
3557 /// [`next()`]: trait.Iterator.html#tymethod.next
3558 ///
3559 /// Because `peek()` returns reference, and many iterators iterate over
3560 /// references, this leads to a possibly confusing situation where the
3561 /// return value is a double reference. You can see this effect in the
3562 /// examples below, with `&&i32`.
3563 ///
3564 /// # Examples
3565 ///
3566 /// Basic usage:
3567 ///
3568 /// ```
3569 /// let xs = [1, 2, 3];
3570 ///
3571 /// let mut iter = xs.iter().peekable();
3572 ///
3573 /// // peek() lets us see into the future
3574 /// assert_eq!(iter.peek(), Some(&&1));
3575 /// assert_eq!(iter.next(), Some(&1));
3576 ///
3577 /// assert_eq!(iter.next(), Some(&2));
3578 ///
3579 /// // we can peek() multiple times, the iterator won't advance
3580 /// assert_eq!(iter.peek(), Some(&&3));
3581 /// assert_eq!(iter.peek(), Some(&&3));
3582 ///
3583 /// assert_eq!(iter.next(), Some(&3));
3584 ///
3585 /// // after the iterator is finished, so is peek()
3586 /// assert_eq!(iter.peek(), None);
3587 /// assert_eq!(iter.next(), None);
3588 /// ```
3589 #[inline]
3590 #[stable(feature = "rust1", since = "1.0.0")]
3591 pub fn peek(&mut self) -> Option<&I::Item> {
3592 if self.peeked.is_none() {
3593 self.peeked = self.iter.next();
3594 }
3595 match self.peeked {
3596 Some(ref value) => Some(value),
3597 None => None,
3598 }
3599 }
3600
3601 /// Checks if the iterator has finished iterating.
3602 ///
3603 /// Returns `true` if there are no more elements in the iterator, and
3604 /// `false` if there are.
3605 ///
3606 /// # Examples
3607 ///
3608 /// Basic usage:
3609 ///
3610 /// ```
3611 /// #![feature(peekable_is_empty)]
3612 ///
3613 /// let xs = [1, 2, 3];
3614 ///
3615 /// let mut iter = xs.iter().peekable();
3616 ///
3617 /// // there are still elements to iterate over
3618 /// assert_eq!(iter.is_empty(), false);
3619 ///
3620 /// // let's consume the iterator
3621 /// iter.next();
3622 /// iter.next();
3623 /// iter.next();
3624 ///
3625 /// assert_eq!(iter.is_empty(), true);
3626 /// ```
3627 #[unstable(feature = "peekable_is_empty", issue = "27701")]
3628 #[inline]
3629 pub fn is_empty(&mut self) -> bool {
3630 self.peek().is_none()
3631 }
3632 }
3633
3634 /// An iterator that rejects elements while `predicate` is true.
3635 ///
3636 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3637 /// documentation for more.
3638 ///
3639 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3640 /// [`Iterator`]: trait.Iterator.html
3641 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3642 #[stable(feature = "rust1", since = "1.0.0")]
3643 #[derive(Clone)]
3644 pub struct SkipWhile<I, P> {
3645 iter: I,
3646 flag: bool,
3647 predicate: P,
3648 }
3649
3650 #[stable(feature = "rust1", since = "1.0.0")]
3651 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3652 where P: FnMut(&I::Item) -> bool
3653 {
3654 type Item = I::Item;
3655
3656 #[inline]
3657 fn next(&mut self) -> Option<I::Item> {
3658 for x in self.iter.by_ref() {
3659 if self.flag || !(self.predicate)(&x) {
3660 self.flag = true;
3661 return Some(x);
3662 }
3663 }
3664 None
3665 }
3666
3667 #[inline]
3668 fn size_hint(&self) -> (usize, Option<usize>) {
3669 let (_, upper) = self.iter.size_hint();
3670 (0, upper) // can't know a lower bound, due to the predicate
3671 }
3672 }
3673
3674 /// An iterator that only accepts elements while `predicate` is true.
3675 ///
3676 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3677 /// documentation for more.
3678 ///
3679 /// [`take_while()`]: trait.Iterator.html#method.take_while
3680 /// [`Iterator`]: trait.Iterator.html
3681 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3682 #[stable(feature = "rust1", since = "1.0.0")]
3683 #[derive(Clone)]
3684 pub struct TakeWhile<I, P> {
3685 iter: I,
3686 flag: bool,
3687 predicate: P,
3688 }
3689
3690 #[stable(feature = "rust1", since = "1.0.0")]
3691 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3692 where P: FnMut(&I::Item) -> bool
3693 {
3694 type Item = I::Item;
3695
3696 #[inline]
3697 fn next(&mut self) -> Option<I::Item> {
3698 if self.flag {
3699 None
3700 } else {
3701 self.iter.next().and_then(|x| {
3702 if (self.predicate)(&x) {
3703 Some(x)
3704 } else {
3705 self.flag = true;
3706 None
3707 }
3708 })
3709 }
3710 }
3711
3712 #[inline]
3713 fn size_hint(&self) -> (usize, Option<usize>) {
3714 let (_, upper) = self.iter.size_hint();
3715 (0, upper) // can't know a lower bound, due to the predicate
3716 }
3717 }
3718
3719 /// An iterator that skips over `n` elements of `iter`.
3720 ///
3721 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3722 /// documentation for more.
3723 ///
3724 /// [`skip()`]: trait.Iterator.html#method.skip
3725 /// [`Iterator`]: trait.Iterator.html
3726 #[derive(Clone)]
3727 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3728 #[stable(feature = "rust1", since = "1.0.0")]
3729 pub struct Skip<I> {
3730 iter: I,
3731 n: usize
3732 }
3733
3734 #[stable(feature = "rust1", since = "1.0.0")]
3735 impl<I> Iterator for Skip<I> where I: Iterator {
3736 type Item = <I as Iterator>::Item;
3737
3738 #[inline]
3739 fn next(&mut self) -> Option<I::Item> {
3740 if self.n == 0 {
3741 self.iter.next()
3742 } else {
3743 let old_n = self.n;
3744 self.n = 0;
3745 self.iter.nth(old_n)
3746 }
3747 }
3748
3749 #[inline]
3750 fn nth(&mut self, n: usize) -> Option<I::Item> {
3751 // Can't just add n + self.n due to overflow.
3752 if self.n == 0 {
3753 self.iter.nth(n)
3754 } else {
3755 let to_skip = self.n;
3756 self.n = 0;
3757 // nth(n) skips n+1
3758 if self.iter.nth(to_skip-1).is_none() {
3759 return None;
3760 }
3761 self.iter.nth(n)
3762 }
3763 }
3764
3765 #[inline]
3766 fn count(self) -> usize {
3767 self.iter.count().saturating_sub(self.n)
3768 }
3769
3770 #[inline]
3771 fn last(mut self) -> Option<I::Item> {
3772 if self.n == 0 {
3773 self.iter.last()
3774 } else {
3775 let next = self.next();
3776 if next.is_some() {
3777 // recurse. n should be 0.
3778 self.last().or(next)
3779 } else {
3780 None
3781 }
3782 }
3783 }
3784
3785 #[inline]
3786 fn size_hint(&self) -> (usize, Option<usize>) {
3787 let (lower, upper) = self.iter.size_hint();
3788
3789 let lower = lower.saturating_sub(self.n);
3790 let upper = upper.map(|x| x.saturating_sub(self.n));
3791
3792 (lower, upper)
3793 }
3794 }
3795
3796 #[stable(feature = "rust1", since = "1.0.0")]
3797 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3798
3799 /// An iterator that only iterates over the first `n` iterations of `iter`.
3800 ///
3801 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3802 /// documentation for more.
3803 ///
3804 /// [`take()`]: trait.Iterator.html#method.take
3805 /// [`Iterator`]: trait.Iterator.html
3806 #[derive(Clone)]
3807 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3808 #[stable(feature = "rust1", since = "1.0.0")]
3809 pub struct Take<I> {
3810 iter: I,
3811 n: usize
3812 }
3813
3814 #[stable(feature = "rust1", since = "1.0.0")]
3815 impl<I> Iterator for Take<I> where I: Iterator{
3816 type Item = <I as Iterator>::Item;
3817
3818 #[inline]
3819 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3820 if self.n != 0 {
3821 self.n -= 1;
3822 self.iter.next()
3823 } else {
3824 None
3825 }
3826 }
3827
3828 #[inline]
3829 fn nth(&mut self, n: usize) -> Option<I::Item> {
3830 if self.n > n {
3831 self.n -= n + 1;
3832 self.iter.nth(n)
3833 } else {
3834 if self.n > 0 {
3835 self.iter.nth(self.n - 1);
3836 self.n = 0;
3837 }
3838 None
3839 }
3840 }
3841
3842 #[inline]
3843 fn size_hint(&self) -> (usize, Option<usize>) {
3844 let (lower, upper) = self.iter.size_hint();
3845
3846 let lower = cmp::min(lower, self.n);
3847
3848 let upper = match upper {
3849 Some(x) if x < self.n => Some(x),
3850 _ => Some(self.n)
3851 };
3852
3853 (lower, upper)
3854 }
3855 }
3856
3857 #[stable(feature = "rust1", since = "1.0.0")]
3858 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3859
3860
3861 /// An iterator to maintain state while iterating another iterator.
3862 ///
3863 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3864 /// documentation for more.
3865 ///
3866 /// [`scan()`]: trait.Iterator.html#method.scan
3867 /// [`Iterator`]: trait.Iterator.html
3868 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3869 #[stable(feature = "rust1", since = "1.0.0")]
3870 #[derive(Clone)]
3871 pub struct Scan<I, St, F> {
3872 iter: I,
3873 f: F,
3874 state: St,
3875 }
3876
3877 #[stable(feature = "rust1", since = "1.0.0")]
3878 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3879 I: Iterator,
3880 F: FnMut(&mut St, I::Item) -> Option<B>,
3881 {
3882 type Item = B;
3883
3884 #[inline]
3885 fn next(&mut self) -> Option<B> {
3886 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3887 }
3888
3889 #[inline]
3890 fn size_hint(&self) -> (usize, Option<usize>) {
3891 let (_, upper) = self.iter.size_hint();
3892 (0, upper) // can't know a lower bound, due to the scan function
3893 }
3894 }
3895
3896 /// An iterator that maps each element to an iterator, and yields the elements
3897 /// of the produced iterators.
3898 ///
3899 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3900 /// documentation for more.
3901 ///
3902 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3903 /// [`Iterator`]: trait.Iterator.html
3904 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3905 #[stable(feature = "rust1", since = "1.0.0")]
3906 #[derive(Clone)]
3907 pub struct FlatMap<I, U: IntoIterator, F> {
3908 iter: I,
3909 f: F,
3910 frontiter: Option<U::IntoIter>,
3911 backiter: Option<U::IntoIter>,
3912 }
3913
3914 #[stable(feature = "rust1", since = "1.0.0")]
3915 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3916 where F: FnMut(I::Item) -> U,
3917 {
3918 type Item = U::Item;
3919
3920 #[inline]
3921 fn next(&mut self) -> Option<U::Item> {
3922 loop {
3923 if let Some(ref mut inner) = self.frontiter {
3924 if let Some(x) = inner.by_ref().next() {
3925 return Some(x)
3926 }
3927 }
3928 match self.iter.next().map(&mut self.f) {
3929 None => return self.backiter.as_mut().and_then(|it| it.next()),
3930 next => self.frontiter = next.map(IntoIterator::into_iter),
3931 }
3932 }
3933 }
3934
3935 #[inline]
3936 fn size_hint(&self) -> (usize, Option<usize>) {
3937 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3938 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3939 let lo = flo.saturating_add(blo);
3940 match (self.iter.size_hint(), fhi, bhi) {
3941 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
3942 _ => (lo, None)
3943 }
3944 }
3945 }
3946
3947 #[stable(feature = "rust1", since = "1.0.0")]
3948 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
3949 F: FnMut(I::Item) -> U,
3950 U: IntoIterator,
3951 U::IntoIter: DoubleEndedIterator
3952 {
3953 #[inline]
3954 fn next_back(&mut self) -> Option<U::Item> {
3955 loop {
3956 if let Some(ref mut inner) = self.backiter {
3957 if let Some(y) = inner.next_back() {
3958 return Some(y)
3959 }
3960 }
3961 match self.iter.next_back().map(&mut self.f) {
3962 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
3963 next => self.backiter = next.map(IntoIterator::into_iter),
3964 }
3965 }
3966 }
3967 }
3968
3969 /// An iterator that yields `None` forever after the underlying iterator
3970 /// yields `None` once.
3971 ///
3972 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3973 /// documentation for more.
3974 ///
3975 /// [`fuse()`]: trait.Iterator.html#method.fuse
3976 /// [`Iterator`]: trait.Iterator.html
3977 #[derive(Clone)]
3978 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3979 #[stable(feature = "rust1", since = "1.0.0")]
3980 pub struct Fuse<I> {
3981 iter: I,
3982 done: bool
3983 }
3984
3985 #[stable(feature = "rust1", since = "1.0.0")]
3986 impl<I> Iterator for Fuse<I> where I: Iterator {
3987 type Item = <I as Iterator>::Item;
3988
3989 #[inline]
3990 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3991 if self.done {
3992 None
3993 } else {
3994 let next = self.iter.next();
3995 self.done = next.is_none();
3996 next
3997 }
3998 }
3999
4000 #[inline]
4001 fn nth(&mut self, n: usize) -> Option<I::Item> {
4002 if self.done {
4003 None
4004 } else {
4005 let nth = self.iter.nth(n);
4006 self.done = nth.is_none();
4007 nth
4008 }
4009 }
4010
4011 #[inline]
4012 fn last(self) -> Option<I::Item> {
4013 if self.done {
4014 None
4015 } else {
4016 self.iter.last()
4017 }
4018 }
4019
4020 #[inline]
4021 fn count(self) -> usize {
4022 if self.done {
4023 0
4024 } else {
4025 self.iter.count()
4026 }
4027 }
4028
4029 #[inline]
4030 fn size_hint(&self) -> (usize, Option<usize>) {
4031 if self.done {
4032 (0, Some(0))
4033 } else {
4034 self.iter.size_hint()
4035 }
4036 }
4037 }
4038
4039 #[stable(feature = "rust1", since = "1.0.0")]
4040 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
4041 #[inline]
4042 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
4043 if self.done {
4044 None
4045 } else {
4046 let next = self.iter.next_back();
4047 self.done = next.is_none();
4048 next
4049 }
4050 }
4051 }
4052
4053 #[stable(feature = "rust1", since = "1.0.0")]
4054 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
4055
4056 /// An iterator that calls a function with a reference to each element before
4057 /// yielding it.
4058 ///
4059 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4060 /// documentation for more.
4061 ///
4062 /// [`inspect()`]: trait.Iterator.html#method.inspect
4063 /// [`Iterator`]: trait.Iterator.html
4064 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4065 #[stable(feature = "rust1", since = "1.0.0")]
4066 #[derive(Clone)]
4067 pub struct Inspect<I, F> {
4068 iter: I,
4069 f: F,
4070 }
4071
4072 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
4073 #[inline]
4074 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
4075 if let Some(ref a) = elt {
4076 (self.f)(a);
4077 }
4078
4079 elt
4080 }
4081 }
4082
4083 #[stable(feature = "rust1", since = "1.0.0")]
4084 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
4085 type Item = I::Item;
4086
4087 #[inline]
4088 fn next(&mut self) -> Option<I::Item> {
4089 let next = self.iter.next();
4090 self.do_inspect(next)
4091 }
4092
4093 #[inline]
4094 fn size_hint(&self) -> (usize, Option<usize>) {
4095 self.iter.size_hint()
4096 }
4097 }
4098
4099 #[stable(feature = "rust1", since = "1.0.0")]
4100 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
4101 where F: FnMut(&I::Item),
4102 {
4103 #[inline]
4104 fn next_back(&mut self) -> Option<I::Item> {
4105 let next = self.iter.next_back();
4106 self.do_inspect(next)
4107 }
4108 }
4109
4110 /// Objects that can be stepped over in both directions.
4111 ///
4112 /// The `steps_between` function provides a way to efficiently compare
4113 /// two `Step` objects.
4114 #[unstable(feature = "step_trait",
4115 reason = "likely to be replaced by finer-grained traits",
4116 issue = "27741")]
4117 pub trait Step: PartialOrd + Sized {
4118 /// Steps `self` if possible.
4119 fn step(&self, by: &Self) -> Option<Self>;
4120
4121 /// Returns the number of steps between two step objects. The count is
4122 /// inclusive of `start` and exclusive of `end`.
4123 ///
4124 /// Returns `None` if it is not possible to calculate `steps_between`
4125 /// without overflow.
4126 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
4127 }
4128
4129 macro_rules! step_impl_unsigned {
4130 ($($t:ty)*) => ($(
4131 #[unstable(feature = "step_trait",
4132 reason = "likely to be replaced by finer-grained traits",
4133 issue = "27741")]
4134 impl Step for $t {
4135 #[inline]
4136 fn step(&self, by: &$t) -> Option<$t> {
4137 (*self).checked_add(*by)
4138 }
4139 #[inline]
4140 #[allow(trivial_numeric_casts)]
4141 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4142 if *by == 0 { return None; }
4143 if *start < *end {
4144 // Note: We assume $t <= usize here
4145 let diff = (*end - *start) as usize;
4146 let by = *by as usize;
4147 if diff % by > 0 {
4148 Some(diff / by + 1)
4149 } else {
4150 Some(diff / by)
4151 }
4152 } else {
4153 Some(0)
4154 }
4155 }
4156 }
4157 )*)
4158 }
4159 macro_rules! step_impl_signed {
4160 ($($t:ty)*) => ($(
4161 #[unstable(feature = "step_trait",
4162 reason = "likely to be replaced by finer-grained traits",
4163 issue = "27741")]
4164 impl Step for $t {
4165 #[inline]
4166 fn step(&self, by: &$t) -> Option<$t> {
4167 (*self).checked_add(*by)
4168 }
4169 #[inline]
4170 #[allow(trivial_numeric_casts)]
4171 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4172 if *by == 0 { return None; }
4173 let diff: usize;
4174 let by_u: usize;
4175 if *by > 0 {
4176 if *start >= *end {
4177 return Some(0);
4178 }
4179 // Note: We assume $t <= isize here
4180 // Use .wrapping_sub and cast to usize to compute the
4181 // difference that may not fit inside the range of isize.
4182 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4183 by_u = *by as usize;
4184 } else {
4185 if *start <= *end {
4186 return Some(0);
4187 }
4188 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4189 by_u = (*by as isize).wrapping_mul(-1) as usize;
4190 }
4191 if diff % by_u > 0 {
4192 Some(diff / by_u + 1)
4193 } else {
4194 Some(diff / by_u)
4195 }
4196 }
4197 }
4198 )*)
4199 }
4200
4201 macro_rules! step_impl_no_between {
4202 ($($t:ty)*) => ($(
4203 #[unstable(feature = "step_trait",
4204 reason = "likely to be replaced by finer-grained traits",
4205 issue = "27741")]
4206 impl Step for $t {
4207 #[inline]
4208 fn step(&self, by: &$t) -> Option<$t> {
4209 (*self).checked_add(*by)
4210 }
4211 #[inline]
4212 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4213 None
4214 }
4215 }
4216 )*)
4217 }
4218
4219 step_impl_unsigned!(usize u8 u16 u32);
4220 step_impl_signed!(isize i8 i16 i32);
4221 #[cfg(target_pointer_width = "64")]
4222 step_impl_unsigned!(u64);
4223 #[cfg(target_pointer_width = "64")]
4224 step_impl_signed!(i64);
4225 // If the target pointer width is not 64-bits, we
4226 // assume here that it is less than 64-bits.
4227 #[cfg(not(target_pointer_width = "64"))]
4228 step_impl_no_between!(u64 i64);
4229
4230 /// An adapter for stepping range iterators by a custom amount.
4231 ///
4232 /// The resulting iterator handles overflow by stopping. The `A`
4233 /// parameter is the type being iterated over, while `R` is the range
4234 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4235 #[derive(Clone)]
4236 #[unstable(feature = "step_by", reason = "recent addition",
4237 issue = "27741")]
4238 pub struct StepBy<A, R> {
4239 step_by: A,
4240 range: R,
4241 }
4242
4243 impl<A: Step> RangeFrom<A> {
4244 /// Creates an iterator starting at the same point, but stepping by
4245 /// the given amount at each iteration.
4246 ///
4247 /// # Examples
4248 ///
4249 /// ```ignore
4250 /// for i in (0u8..).step_by(2) {
4251 /// println!("{}", i);
4252 /// }
4253 /// ```
4254 ///
4255 /// This prints all even `u8` values.
4256 #[unstable(feature = "step_by", reason = "recent addition",
4257 issue = "27741")]
4258 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4259 StepBy {
4260 step_by: by,
4261 range: self
4262 }
4263 }
4264 }
4265
4266 impl<A: Step> ops::Range<A> {
4267 /// Creates an iterator with the same range, but stepping by the
4268 /// given amount at each iteration.
4269 ///
4270 /// The resulting iterator handles overflow by stopping.
4271 ///
4272 /// # Examples
4273 ///
4274 /// ```
4275 /// #![feature(step_by)]
4276 ///
4277 /// for i in (0..10).step_by(2) {
4278 /// println!("{}", i);
4279 /// }
4280 /// ```
4281 ///
4282 /// This prints:
4283 ///
4284 /// ```text
4285 /// 0
4286 /// 2
4287 /// 4
4288 /// 6
4289 /// 8
4290 /// ```
4291 #[unstable(feature = "step_by", reason = "recent addition",
4292 issue = "27741")]
4293 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4294 StepBy {
4295 step_by: by,
4296 range: self
4297 }
4298 }
4299 }
4300
4301 #[stable(feature = "rust1", since = "1.0.0")]
4302 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
4303 A: Clone,
4304 for<'a> &'a A: Add<&'a A, Output = A>
4305 {
4306 type Item = A;
4307
4308 #[inline]
4309 fn next(&mut self) -> Option<A> {
4310 let mut n = &self.range.start + &self.step_by;
4311 mem::swap(&mut n, &mut self.range.start);
4312 Some(n)
4313 }
4314
4315 #[inline]
4316 fn size_hint(&self) -> (usize, Option<usize>) {
4317 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4318 }
4319 }
4320
4321 /// An iterator over the range [start, stop]
4322 #[derive(Clone)]
4323 #[unstable(feature = "range_inclusive",
4324 reason = "likely to be replaced by range notation and adapters",
4325 issue = "27777")]
4326 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4327 #[allow(deprecated)]
4328 pub struct RangeInclusive<A> {
4329 range: ops::Range<A>,
4330 done: bool,
4331 }
4332
4333 /// Returns an iterator over the range [start, stop].
4334 #[inline]
4335 #[unstable(feature = "range_inclusive",
4336 reason = "likely to be replaced by range notation and adapters",
4337 issue = "27777")]
4338 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4339 #[allow(deprecated)]
4340 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
4341 where A: Step + One + Clone
4342 {
4343 RangeInclusive {
4344 range: start..stop,
4345 done: false,
4346 }
4347 }
4348
4349 #[unstable(feature = "range_inclusive",
4350 reason = "likely to be replaced by range notation and adapters",
4351 issue = "27777")]
4352 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4353 #[allow(deprecated)]
4354 impl<A> Iterator for RangeInclusive<A> where
4355 A: PartialEq + Step + One + Clone,
4356 for<'a> &'a A: Add<&'a A, Output = A>
4357 {
4358 type Item = A;
4359
4360 #[inline]
4361 fn next(&mut self) -> Option<A> {
4362 self.range.next().or_else(|| {
4363 if !self.done && self.range.start == self.range.end {
4364 self.done = true;
4365 Some(self.range.end.clone())
4366 } else {
4367 None
4368 }
4369 })
4370 }
4371
4372 #[inline]
4373 fn size_hint(&self) -> (usize, Option<usize>) {
4374 let (lo, hi) = self.range.size_hint();
4375 if self.done {
4376 (lo, hi)
4377 } else {
4378 let lo = lo.saturating_add(1);
4379 let hi = hi.and_then(|x| x.checked_add(1));
4380 (lo, hi)
4381 }
4382 }
4383 }
4384
4385 #[unstable(feature = "range_inclusive",
4386 reason = "likely to be replaced by range notation and adapters",
4387 issue = "27777")]
4388 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4389 #[allow(deprecated)]
4390 impl<A> DoubleEndedIterator for RangeInclusive<A> where
4391 A: PartialEq + Step + One + Clone,
4392 for<'a> &'a A: Add<&'a A, Output = A>,
4393 for<'a> &'a A: Sub<Output=A>
4394 {
4395 #[inline]
4396 fn next_back(&mut self) -> Option<A> {
4397 if self.range.end > self.range.start {
4398 let result = self.range.end.clone();
4399 self.range.end = &self.range.end - &A::one();
4400 Some(result)
4401 } else if !self.done && self.range.start == self.range.end {
4402 self.done = true;
4403 Some(self.range.end.clone())
4404 } else {
4405 None
4406 }
4407 }
4408 }
4409
4410 #[stable(feature = "rust1", since = "1.0.0")]
4411 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4412 type Item = A;
4413
4414 #[inline]
4415 fn next(&mut self) -> Option<A> {
4416 let rev = self.step_by < A::zero();
4417 if (rev && self.range.start > self.range.end) ||
4418 (!rev && self.range.start < self.range.end)
4419 {
4420 match self.range.start.step(&self.step_by) {
4421 Some(mut n) => {
4422 mem::swap(&mut self.range.start, &mut n);
4423 Some(n)
4424 },
4425 None => {
4426 let mut n = self.range.end.clone();
4427 mem::swap(&mut self.range.start, &mut n);
4428 Some(n)
4429 }
4430 }
4431 } else {
4432 None
4433 }
4434 }
4435
4436 #[inline]
4437 fn size_hint(&self) -> (usize, Option<usize>) {
4438 match Step::steps_between(&self.range.start,
4439 &self.range.end,
4440 &self.step_by) {
4441 Some(hint) => (hint, Some(hint)),
4442 None => (0, None)
4443 }
4444 }
4445 }
4446
4447 macro_rules! range_exact_iter_impl {
4448 ($($t:ty)*) => ($(
4449 #[stable(feature = "rust1", since = "1.0.0")]
4450 impl ExactSizeIterator for ops::Range<$t> { }
4451 )*)
4452 }
4453
4454 #[stable(feature = "rust1", since = "1.0.0")]
4455 impl<A: Step + One> Iterator for ops::Range<A> where
4456 for<'a> &'a A: Add<&'a A, Output = A>
4457 {
4458 type Item = A;
4459
4460 #[inline]
4461 fn next(&mut self) -> Option<A> {
4462 if self.start < self.end {
4463 let mut n = &self.start + &A::one();
4464 mem::swap(&mut n, &mut self.start);
4465 Some(n)
4466 } else {
4467 None
4468 }
4469 }
4470
4471 #[inline]
4472 fn size_hint(&self) -> (usize, Option<usize>) {
4473 match Step::steps_between(&self.start, &self.end, &A::one()) {
4474 Some(hint) => (hint, Some(hint)),
4475 None => (0, None)
4476 }
4477 }
4478 }
4479
4480 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4481 // a length <= usize::MAX, which is required by ExactSizeIterator.
4482 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4483
4484 #[stable(feature = "rust1", since = "1.0.0")]
4485 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4486 for<'a> &'a A: Add<&'a A, Output = A>,
4487 for<'a> &'a A: Sub<&'a A, Output = A>
4488 {
4489 #[inline]
4490 fn next_back(&mut self) -> Option<A> {
4491 if self.start < self.end {
4492 self.end = &self.end - &A::one();
4493 Some(self.end.clone())
4494 } else {
4495 None
4496 }
4497 }
4498 }
4499
4500 #[stable(feature = "rust1", since = "1.0.0")]
4501 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4502 for<'a> &'a A: Add<&'a A, Output = A>
4503 {
4504 type Item = A;
4505
4506 #[inline]
4507 fn next(&mut self) -> Option<A> {
4508 let mut n = &self.start + &A::one();
4509 mem::swap(&mut n, &mut self.start);
4510 Some(n)
4511 }
4512 }
4513
4514 /// An iterator that repeats an element endlessly.
4515 ///
4516 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4517 ///
4518 /// [`repeat()`]: fn.repeat.html
4519 #[derive(Clone)]
4520 #[stable(feature = "rust1", since = "1.0.0")]
4521 pub struct Repeat<A> {
4522 element: A
4523 }
4524
4525 #[stable(feature = "rust1", since = "1.0.0")]
4526 impl<A: Clone> Iterator for Repeat<A> {
4527 type Item = A;
4528
4529 #[inline]
4530 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4531 #[inline]
4532 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4533 }
4534
4535 #[stable(feature = "rust1", since = "1.0.0")]
4536 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4537 #[inline]
4538 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4539 }
4540
4541 /// Creates a new iterator that endlessly repeats a single element.
4542 ///
4543 /// The `repeat()` function repeats a single value over and over and over and
4544 /// over and over and 🔁.
4545 ///
4546 /// Infinite iterators like `repeat()` are often used with adapters like
4547 /// [`take()`], in order to make them finite.
4548 ///
4549 /// [`take()`]: trait.Iterator.html#method.take
4550 ///
4551 /// # Examples
4552 ///
4553 /// Basic usage:
4554 ///
4555 /// ```
4556 /// use std::iter;
4557 ///
4558 /// // the number four 4ever:
4559 /// let mut fours = iter::repeat(4);
4560 ///
4561 /// assert_eq!(Some(4), fours.next());
4562 /// assert_eq!(Some(4), fours.next());
4563 /// assert_eq!(Some(4), fours.next());
4564 /// assert_eq!(Some(4), fours.next());
4565 /// assert_eq!(Some(4), fours.next());
4566 ///
4567 /// // yup, still four
4568 /// assert_eq!(Some(4), fours.next());
4569 /// ```
4570 ///
4571 /// Going finite with [`take()`]:
4572 ///
4573 /// ```
4574 /// use std::iter;
4575 ///
4576 /// // that last example was too many fours. Let's only have four fours.
4577 /// let mut four_fours = iter::repeat(4).take(4);
4578 ///
4579 /// assert_eq!(Some(4), four_fours.next());
4580 /// assert_eq!(Some(4), four_fours.next());
4581 /// assert_eq!(Some(4), four_fours.next());
4582 /// assert_eq!(Some(4), four_fours.next());
4583 ///
4584 /// // ... and now we're done
4585 /// assert_eq!(None, four_fours.next());
4586 /// ```
4587 #[inline]
4588 #[stable(feature = "rust1", since = "1.0.0")]
4589 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4590 Repeat{element: elt}
4591 }
4592
4593 /// An iterator that yields nothing.
4594 ///
4595 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4596 ///
4597 /// [`empty()`]: fn.empty.html
4598 #[stable(feature = "iter_empty", since = "1.2.0")]
4599 pub struct Empty<T>(marker::PhantomData<T>);
4600
4601 #[stable(feature = "iter_empty", since = "1.2.0")]
4602 impl<T> Iterator for Empty<T> {
4603 type Item = T;
4604
4605 fn next(&mut self) -> Option<T> {
4606 None
4607 }
4608
4609 fn size_hint(&self) -> (usize, Option<usize>){
4610 (0, Some(0))
4611 }
4612 }
4613
4614 #[stable(feature = "iter_empty", since = "1.2.0")]
4615 impl<T> DoubleEndedIterator for Empty<T> {
4616 fn next_back(&mut self) -> Option<T> {
4617 None
4618 }
4619 }
4620
4621 #[stable(feature = "iter_empty", since = "1.2.0")]
4622 impl<T> ExactSizeIterator for Empty<T> {
4623 fn len(&self) -> usize {
4624 0
4625 }
4626 }
4627
4628 // not #[derive] because that adds a Clone bound on T,
4629 // which isn't necessary.
4630 #[stable(feature = "iter_empty", since = "1.2.0")]
4631 impl<T> Clone for Empty<T> {
4632 fn clone(&self) -> Empty<T> {
4633 Empty(marker::PhantomData)
4634 }
4635 }
4636
4637 // not #[derive] because that adds a Default bound on T,
4638 // which isn't necessary.
4639 #[stable(feature = "iter_empty", since = "1.2.0")]
4640 impl<T> Default for Empty<T> {
4641 fn default() -> Empty<T> {
4642 Empty(marker::PhantomData)
4643 }
4644 }
4645
4646 /// Creates an iterator that yields nothing.
4647 ///
4648 /// # Examples
4649 ///
4650 /// Basic usage:
4651 ///
4652 /// ```
4653 /// use std::iter;
4654 ///
4655 /// // this could have been an iterator over i32, but alas, it's just not.
4656 /// let mut nope = iter::empty::<i32>();
4657 ///
4658 /// assert_eq!(None, nope.next());
4659 /// ```
4660 #[stable(feature = "iter_empty", since = "1.2.0")]
4661 pub fn empty<T>() -> Empty<T> {
4662 Empty(marker::PhantomData)
4663 }
4664
4665 /// An iterator that yields an element exactly once.
4666 ///
4667 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4668 ///
4669 /// [`once()`]: fn.once.html
4670 #[derive(Clone)]
4671 #[stable(feature = "iter_once", since = "1.2.0")]
4672 pub struct Once<T> {
4673 inner: ::option::IntoIter<T>
4674 }
4675
4676 #[stable(feature = "iter_once", since = "1.2.0")]
4677 impl<T> Iterator for Once<T> {
4678 type Item = T;
4679
4680 fn next(&mut self) -> Option<T> {
4681 self.inner.next()
4682 }
4683
4684 fn size_hint(&self) -> (usize, Option<usize>) {
4685 self.inner.size_hint()
4686 }
4687 }
4688
4689 #[stable(feature = "iter_once", since = "1.2.0")]
4690 impl<T> DoubleEndedIterator for Once<T> {
4691 fn next_back(&mut self) -> Option<T> {
4692 self.inner.next_back()
4693 }
4694 }
4695
4696 #[stable(feature = "iter_once", since = "1.2.0")]
4697 impl<T> ExactSizeIterator for Once<T> {
4698 fn len(&self) -> usize {
4699 self.inner.len()
4700 }
4701 }
4702
4703 /// Creates an iterator that yields an element exactly once.
4704 ///
4705 /// This is commonly used to adapt a single value into a [`chain()`] of other
4706 /// kinds of iteration. Maybe you have an iterator that covers almost
4707 /// everything, but you need an extra special case. Maybe you have a function
4708 /// which works on iterators, but you only need to process one value.
4709 ///
4710 /// [`chain()`]: trait.Iterator.html#method.chain
4711 ///
4712 /// # Examples
4713 ///
4714 /// Basic usage:
4715 ///
4716 /// ```
4717 /// use std::iter;
4718 ///
4719 /// // one is the loneliest number
4720 /// let mut one = iter::once(1);
4721 ///
4722 /// assert_eq!(Some(1), one.next());
4723 ///
4724 /// // just one, that's all we get
4725 /// assert_eq!(None, one.next());
4726 /// ```
4727 ///
4728 /// Chaining together with another iterator. Let's say that we want to iterate
4729 /// over each file of the `.foo` directory, but also a configuration file,
4730 /// `.foorc`:
4731 ///
4732 /// ```no_run
4733 /// use std::iter;
4734 /// use std::fs;
4735 /// use std::path::PathBuf;
4736 ///
4737 /// let dirs = fs::read_dir(".foo").unwrap();
4738 ///
4739 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4740 /// // PathBufs, so we use map
4741 /// let dirs = dirs.map(|file| file.unwrap().path());
4742 ///
4743 /// // now, our iterator just for our config file
4744 /// let config = iter::once(PathBuf::from(".foorc"));
4745 ///
4746 /// // chain the two iterators together into one big iterator
4747 /// let files = dirs.chain(config);
4748 ///
4749 /// // this will give us all of the files in .foo as well as .foorc
4750 /// for f in files {
4751 /// println!("{:?}", f);
4752 /// }
4753 /// ```
4754 #[stable(feature = "iter_once", since = "1.2.0")]
4755 pub fn once<T>(value: T) -> Once<T> {
4756 Once { inner: Some(value).into_iter() }
4757 }