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, 4, 5, 6];
376 /// let mut iter = numbers.iter();
378 /// assert_eq!(Some(&1), iter.next());
379 /// assert_eq!(Some(&6), iter.next_back());
380 /// assert_eq!(Some(&5), iter.next_back());
381 /// assert_eq!(Some(&2), iter.next());
382 /// assert_eq!(Some(&3), iter.next());
383 /// assert_eq!(Some(&4), iter.next());
384 /// assert_eq!(None, iter.next());
385 /// assert_eq!(None, iter.next_back());
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub trait DoubleEndedIterator
: Iterator
{
389 /// Removes and returns an element from the end of the iterator.
391 /// Returns `None` when there are no more elements.
393 /// The [trait-level] docs contain more details.
395 /// [trait-level]: trait.DoubleEndedIterator.html
402 /// let numbers = vec![1, 2, 3, 4, 5, 6];
404 /// let mut iter = numbers.iter();
406 /// assert_eq!(Some(&1), iter.next());
407 /// assert_eq!(Some(&6), iter.next_back());
408 /// assert_eq!(Some(&5), iter.next_back());
409 /// assert_eq!(Some(&2), iter.next());
410 /// assert_eq!(Some(&3), iter.next());
411 /// assert_eq!(Some(&4), iter.next());
412 /// assert_eq!(None, iter.next());
413 /// assert_eq!(None, iter.next_back());
415 #[stable(feature = "rust1", since = "1.0.0")]
416 fn next_back(&mut self) -> Option
<Self::Item
>;
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl<'a
, I
: DoubleEndedIterator
+ ?Sized
> DoubleEndedIterator
for &'a
mut I
{
421 fn next_back(&mut self) -> Option
<I
::Item
> { (**self).next_back() }
424 /// An iterator that knows its exact length.
426 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
427 /// If an iterator knows how many times it can iterate, providing access to
428 /// that information can be useful. For example, if you want to iterate
429 /// backwards, a good start is to know where the end is.
431 /// When implementing an `ExactSizeIterator`, You must also implement
432 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
433 /// return the exact size of the iterator.
435 /// [`Iterator`]: trait.Iterator.html
436 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
438 /// The [`len()`] method has a default implementation, so you usually shouldn't
439 /// implement it. However, you may be able to provide a more performant
440 /// implementation than the default, so overriding it in this case makes sense.
442 /// [`len()`]: #method.len
449 /// // a finite range knows exactly how many times it will iterate
452 /// assert_eq!(5, five.len());
455 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
456 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
458 /// [moddocs]: index.html
461 /// # struct Counter {
465 /// # fn new() -> Counter {
466 /// # Counter { count: 0 }
469 /// # impl Iterator for Counter {
470 /// # type Item = usize;
471 /// # fn next(&mut self) -> Option<usize> {
472 /// # self.count += 1;
473 /// # if self.count < 6 {
474 /// # Some(self.count)
480 /// impl ExactSizeIterator for Counter {
481 /// // We already have the number of iterations, so we can use it directly.
482 /// fn len(&self) -> usize {
487 /// // And now we can use it!
489 /// let counter = Counter::new();
491 /// assert_eq!(0, counter.len());
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub trait ExactSizeIterator
: Iterator
{
495 /// Returns the exact number of times the iterator will iterate.
497 /// This method has a default implementation, so you usually should not
498 /// implement it directly. However, if you can provide a more efficient
499 /// implementation, you can do so. See the [trait-level] docs for an
502 /// This function has the same safety guarantees as the [`size_hint()`]
505 /// [trait-level]: trait.ExactSizeIterator.html
506 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
513 /// // a finite range knows exactly how many times it will iterate
516 /// assert_eq!(5, five.len());
519 #[stable(feature = "rust1", since = "1.0.0")]
520 fn len(&self) -> usize {
521 let (lower
, upper
) = self.size_hint();
522 // Note: This assertion is overly defensive, but it checks the invariant
523 // guaranteed by the trait. If this trait were rust-internal,
524 // we could use debug_assert!; assert_eq! will check all Rust user
525 // implementations too.
526 assert_eq
!(upper
, Some(lower
));
530 /// Returns whether the iterator is empty.
532 /// This method has a default implementation using `self.len()`, so you
533 /// don't need to implement it yourself.
540 /// #![feature(exact_size_is_empty)]
542 /// let mut one_element = 0..1;
543 /// assert!(!one_element.is_empty());
545 /// assert_eq!(one_element.next(), Some(0));
546 /// assert!(one_element.is_empty());
548 /// assert_eq!(one_element.next(), None);
551 #[unstable(feature = "exact_size_is_empty", issue = "35428")]
552 fn is_empty(&self) -> bool
{
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<'a
, I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for &'a
mut I {}
560 /// Trait to represent types that can be created by summing up an iterator.
562 /// This trait is used to implement the `sum` method on iterators. Types which
563 /// implement the trait can be generated by the `sum` method. Like
564 /// `FromIterator` this trait should rarely be called directly and instead
565 /// interacted with through `Iterator::sum`.
566 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
567 pub trait Sum
<A
= Self>: Sized
{
568 /// Method which takes an iterator and generates `Self` from the elements by
569 /// "summing up" the items.
570 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
571 fn sum
<I
: Iterator
<Item
=A
>>(iter
: I
) -> Self;
574 /// Trait to represent types that can be created by multiplying elements of an
577 /// This trait is used to implement the `product` method on iterators. Types
578 /// which implement the trait can be generated by the `product` method. Like
579 /// `FromIterator` this trait should rarely be called directly and instead
580 /// interacted with through `Iterator::product`.
581 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
582 pub trait Product
<A
= Self>: Sized
{
583 /// Method which takes an iterator and generates `Self` from the elements by
584 /// multiplying the items.
585 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
586 fn product
<I
: Iterator
<Item
=A
>>(iter
: I
) -> Self;
589 macro_rules
! integer_sum_product
{
590 ($
($a
:ident
)*) => ($
(
591 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
593 fn sum
<I
: Iterator
<Item
=$a
>>(iter
: I
) -> $a
{
594 iter
.fold(0, |a
, b
| {
595 a
.checked_add(b
).expect("overflow in sum")
600 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
601 impl Product
for $a
{
602 fn product
<I
: Iterator
<Item
=$a
>>(iter
: I
) -> $a
{
603 iter
.fold(1, |a
, b
| {
604 a
.checked_mul(b
).expect("overflow in product")
609 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
610 impl<'a
> Sum
<&'a $a
> for $a
{
611 fn sum
<I
: Iterator
<Item
=&'a $a
>>(iter
: I
) -> $a
{
612 iter
.fold(0, |a
, b
| {
613 a
.checked_add(*b
).expect("overflow in sum")
618 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
619 impl<'a
> Product
<&'a $a
> for $a
{
620 fn product
<I
: Iterator
<Item
=&'a $a
>>(iter
: I
) -> $a
{
621 iter
.fold(1, |a
, b
| {
622 a
.checked_mul(*b
).expect("overflow in product")
629 macro_rules
! float_sum_product
{
630 ($
($a
:ident
)*) => ($
(
631 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
633 fn sum
<I
: Iterator
<Item
=$a
>>(iter
: I
) -> $a
{
634 iter
.fold(0.0, |a
, b
| a
+ b
)
638 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
639 impl Product
for $a
{
640 fn product
<I
: Iterator
<Item
=$a
>>(iter
: I
) -> $a
{
641 iter
.fold(1.0, |a
, b
| a
* b
)
645 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
646 impl<'a
> Sum
<&'a $a
> for $a
{
647 fn sum
<I
: Iterator
<Item
=&'a $a
>>(iter
: I
) -> $a
{
648 iter
.fold(0.0, |a
, b
| a
+ *b
)
652 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
653 impl<'a
> Product
<&'a $a
> for $a
{
654 fn product
<I
: Iterator
<Item
=&'a $a
>>(iter
: I
) -> $a
{
655 iter
.fold(1.0, |a
, b
| a
* *b
)
661 integer_sum_product
! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
662 float_sum_product
! { f32 f64 }