1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use option::Option::{self, Some};
16 /// Conversion from an `Iterator`.
18 /// By implementing `FromIterator` for a type, you define how it will be
19 /// created from an iterator. This is common for types which describe a
20 /// collection of some kind.
22 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
23 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
24 /// documentation for more examples.
26 /// [`from_iter()`]: #tymethod.from_iter
27 /// [`Iterator`]: trait.Iterator.html
28 /// [`collect()`]: trait.Iterator.html#method.collect
30 /// See also: [`IntoIterator`].
32 /// [`IntoIterator`]: trait.IntoIterator.html
39 /// use std::iter::FromIterator;
41 /// let five_fives = std::iter::repeat(5).take(5);
43 /// let v = Vec::from_iter(five_fives);
45 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
48 /// Using [`collect()`] to implicitly use `FromIterator`:
51 /// let five_fives = std::iter::repeat(5).take(5);
53 /// let v: Vec<i32> = five_fives.collect();
55 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
58 /// Implementing `FromIterator` for your type:
61 /// use std::iter::FromIterator;
63 /// // A sample collection, that's just a wrapper over Vec<T>
65 /// struct MyCollection(Vec<i32>);
67 /// // Let's give it some methods so we can create one and add things
69 /// impl MyCollection {
70 /// fn new() -> MyCollection {
71 /// MyCollection(Vec::new())
74 /// fn add(&mut self, elem: i32) {
75 /// self.0.push(elem);
79 /// // and we'll implement FromIterator
80 /// impl FromIterator<i32> for MyCollection {
81 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
82 /// let mut c = MyCollection::new();
92 /// // Now we can make a new iterator...
93 /// let iter = (0..5).into_iter();
95 /// // ... and make a MyCollection out of it
96 /// let c = MyCollection::from_iter(iter);
98 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
100 /// // collect works too!
102 /// let iter = (0..5).into_iter();
103 /// let c: MyCollection = iter.collect();
105 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
107 #[stable(feature = "rust1", since = "1.0.0")]
108 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
109 built from an iterator over elements of type `{A}`"]
110 pub trait FromIterator<A>: Sized {
111 /// Creates a value from an iterator.
113 /// See the [module-level documentation] for more.
115 /// [module-level documentation]: trait.FromIterator.html
122 /// use std::iter::FromIterator;
124 /// let five_fives = std::iter::repeat(5).take(5);
126 /// let v = Vec::from_iter(five_fives);
128 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
130 #[stable(feature = "rust1", since = "1.0.0")]
131 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
134 /// Conversion into an `Iterator`.
136 /// By implementing `IntoIterator` for a type, you define how it will be
137 /// converted to an iterator. This is common for types which describe a
138 /// collection of some kind.
140 /// One benefit of implementing `IntoIterator` is that your type will [work
141 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
143 /// See also: [`FromIterator`].
145 /// [`FromIterator`]: trait.FromIterator.html
152 /// let v = vec![1, 2, 3];
154 /// let mut iter = v.into_iter();
156 /// let n = iter.next();
157 /// assert_eq!(Some(1), n);
159 /// let n = iter.next();
160 /// assert_eq!(Some(2), n);
162 /// let n = iter.next();
163 /// assert_eq!(Some(3), n);
165 /// let n = iter.next();
166 /// assert_eq!(None, n);
169 /// Implementing `IntoIterator` for your type:
172 /// // A sample collection, that's just a wrapper over Vec<T>
174 /// struct MyCollection(Vec<i32>);
176 /// // Let's give it some methods so we can create one and add things
178 /// impl MyCollection {
179 /// fn new() -> MyCollection {
180 /// MyCollection(Vec::new())
183 /// fn add(&mut self, elem: i32) {
184 /// self.0.push(elem);
188 /// // and we'll implement IntoIterator
189 /// impl IntoIterator for MyCollection {
191 /// type IntoIter = ::std::vec::IntoIter<i32>;
193 /// fn into_iter(self) -> Self::IntoIter {
194 /// self.0.into_iter()
198 /// // Now we can make a new collection...
199 /// let mut c = MyCollection::new();
201 /// // ... add some stuff to it ...
206 /// // ... and then turn it into an Iterator:
207 /// for (i, n) in c.into_iter().enumerate() {
208 /// assert_eq!(i as i32, n);
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub trait IntoIterator {
213 /// The type of the elements being iterated over.
214 #[stable(feature = "rust1", since = "1.0.0")]
217 /// Which kind of iterator are we turning this into?
218 #[stable(feature = "rust1", since = "1.0.0")]
219 type IntoIter: Iterator<Item=Self::Item>;
221 /// Creates an iterator from a value.
223 /// See the [module-level documentation] for more.
225 /// [module-level documentation]: trait.IntoIterator.html
232 /// let v = vec![1, 2, 3];
234 /// let mut iter = v.into_iter();
236 /// let n = iter.next();
237 /// assert_eq!(Some(1), n);
239 /// let n = iter.next();
240 /// assert_eq!(Some(2), n);
242 /// let n = iter.next();
243 /// assert_eq!(Some(3), n);
245 /// let n = iter.next();
246 /// assert_eq!(None, n);
248 #[stable(feature = "rust1", since = "1.0.0")]
249 fn into_iter(self) -> Self::IntoIter;
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<I: Iterator> IntoIterator for I {
257 fn into_iter(self) -> I {
262 /// Extend a collection with the contents of an iterator.
264 /// Iterators produce a series of values, and collections can also be thought
265 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
266 /// to extend a collection by including the contents of that iterator.
273 /// // You can extend a String with some chars:
274 /// let mut message = String::from("The first three letters are: ");
276 /// message.extend(&['a', 'b', 'c']);
278 /// assert_eq!("abc", &message[29..32]);
281 /// Implementing `Extend`:
284 /// // A sample collection, that's just a wrapper over Vec<T>
286 /// struct MyCollection(Vec<i32>);
288 /// // Let's give it some methods so we can create one and add things
290 /// impl MyCollection {
291 /// fn new() -> MyCollection {
292 /// MyCollection(Vec::new())
295 /// fn add(&mut self, elem: i32) {
296 /// self.0.push(elem);
300 /// // since MyCollection has a list of i32s, we implement Extend for i32
301 /// impl Extend<i32> for MyCollection {
303 /// // This is a bit simpler with the concrete type signature: we can call
304 /// // extend on anything which can be turned into an Iterator which gives
305 /// // us i32s. Because we need i32s to put into MyCollection.
306 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
308 /// // The implementation is very straightforward: loop through the
309 /// // iterator, and add() each element to ourselves.
310 /// for elem in iter {
316 /// let mut c = MyCollection::new();
322 /// // let's extend our collection with three more numbers
323 /// c.extend(vec![1, 2, 3]);
325 /// // we've added these elements onto the end
326 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub trait Extend<A> {
330 /// Extends a collection with the contents of an iterator.
332 /// As this is the only method for this trait, the [trait-level] docs
333 /// contain more details.
335 /// [trait-level]: trait.Extend.html
342 /// // You can extend a String with some chars:
343 /// let mut message = String::from("abc");
345 /// message.extend(['d', 'e', 'f'].iter());
347 /// assert_eq!("abcdef", &message);
349 #[stable(feature = "rust1", since = "1.0.0")]
350 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
353 /// An iterator able to yield elements from both ends.
355 /// Something that implements `DoubleEndedIterator` has one extra capability
356 /// over something that implements [`Iterator`]: the ability to also take
357 /// `Item`s from the back, as well as the front.
359 /// It is important to note that both back and forth work on the same range,
360 /// and do not cross: iteration is over when they meet in the middle.
362 /// In a similar fashion to the [`Iterator`] protocol, once a
363 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
364 /// may or may not ever return `Some` again. `next()` and `next_back()` are
365 /// interchangable for this purpose.
367 /// [`Iterator`]: trait.Iterator.html
374 /// let numbers = vec![1, 2, 3];
376 /// let mut iter = numbers.iter();
378 /// assert_eq!(Some(&1), iter.next());
379 /// assert_eq!(Some(&3), iter.next_back());
380 /// assert_eq!(Some(&2), iter.next_back());
381 /// assert_eq!(None, iter.next());
382 /// assert_eq!(None, iter.next_back());
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub trait DoubleEndedIterator: Iterator {
386 /// An iterator able to yield elements from both ends.
388 /// As this is the only method for this trait, the [trait-level] docs
389 /// contain more details.
391 /// [trait-level]: trait.DoubleEndedIterator.html
398 /// let numbers = vec![1, 2, 3];
400 /// let mut iter = numbers.iter();
402 /// assert_eq!(Some(&1), iter.next());
403 /// assert_eq!(Some(&3), iter.next_back());
404 /// assert_eq!(Some(&2), iter.next_back());
405 /// assert_eq!(None, iter.next());
406 /// assert_eq!(None, iter.next_back());
408 #[stable(feature = "rust1", since = "1.0.0")]
409 fn next_back(&mut self) -> Option<Self::Item>;
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
414 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
417 /// An iterator that knows its exact length.
419 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
420 /// If an iterator knows how many times it can iterate, providing access to
421 /// that information can be useful. For example, if you want to iterate
422 /// backwards, a good start is to know where the end is.
424 /// When implementing an `ExactSizeIterator`, You must also implement
425 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
426 /// return the exact size of the iterator.
428 /// [`Iterator`]: trait.Iterator.html
429 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
431 /// The [`len()`] method has a default implementation, so you usually shouldn't
432 /// implement it. However, you may be able to provide a more performant
433 /// implementation than the default, so overriding it in this case makes sense.
435 /// [`len()`]: #method.len
442 /// // a finite range knows exactly how many times it will iterate
445 /// assert_eq!(5, five.len());
448 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
449 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
451 /// [moddocs]: index.html
454 /// # struct Counter {
458 /// # fn new() -> Counter {
459 /// # Counter { count: 0 }
462 /// # impl Iterator for Counter {
463 /// # type Item = usize;
464 /// # fn next(&mut self) -> Option<usize> {
465 /// # self.count += 1;
466 /// # if self.count < 6 {
467 /// # Some(self.count)
473 /// impl ExactSizeIterator for Counter {
474 /// // We already have the number of iterations, so we can use it directly.
475 /// fn len(&self) -> usize {
480 /// // And now we can use it!
482 /// let counter = Counter::new();
484 /// assert_eq!(0, counter.len());
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub trait ExactSizeIterator: Iterator {
488 /// Returns the exact number of times the iterator will iterate.
490 /// This method has a default implementation, so you usually should not
491 /// implement it directly. However, if you can provide a more efficient
492 /// implementation, you can do so. See the [trait-level] docs for an
495 /// This function has the same safety guarantees as the [`size_hint()`]
498 /// [trait-level]: trait.ExactSizeIterator.html
499 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
506 /// // a finite range knows exactly how many times it will iterate
509 /// assert_eq!(5, five.len());
512 #[stable(feature = "rust1", since = "1.0.0")]
513 fn len(&self) -> usize {
514 let (lower, upper) = self.size_hint();
515 // Note: This assertion is overly defensive, but it checks the invariant
516 // guaranteed by the trait. If this trait were rust-internal,
517 // we could use debug_assert!; assert_eq! will check all Rust user
518 // implementations too.
519 assert_eq!(upper, Some(lower));
524 /// Returns whether the iterator is empty.
526 /// This method has a default implementation using `self.len()`, so you
527 /// don't need to implement it yourself.
534 /// let mut one_element = [0].iter();
535 /// assert!(!one_element.is_empty());
537 /// assert_eq!(one_element.next(), Some(0));
538 /// assert!(one_element.is_empty());
540 /// assert_eq!(one_element.next(), None);
543 #[unstable(feature = "exact_size_is_empty", issue = "0")]
544 fn is_empty(&self) -> bool {
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}