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.
10 use ops::{Mul, Add, Try};
15 /// Conversion from an `Iterator`.
17 /// By implementing `FromIterator` for a type, you define how it will be
18 /// created from an iterator. This is common for types which describe a
19 /// collection of some kind.
21 /// `FromIterator`'s [`from_iter`] is rarely called explicitly, and is instead
22 /// used through [`Iterator`]'s [`collect`] method. See [`collect`]'s
23 /// documentation for more examples.
25 /// [`from_iter`]: #tymethod.from_iter
26 /// [`Iterator`]: trait.Iterator.html
27 /// [`collect`]: trait.Iterator.html#method.collect
29 /// See also: [`IntoIterator`].
31 /// [`IntoIterator`]: trait.IntoIterator.html
38 /// use std::iter::FromIterator;
40 /// let five_fives = std::iter::repeat(5).take(5);
42 /// let v = Vec::from_iter(five_fives);
44 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
47 /// Using [`collect`] to implicitly use `FromIterator`:
50 /// let five_fives = std::iter::repeat(5).take(5);
52 /// let v: Vec<i32> = five_fives.collect();
54 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
57 /// Implementing `FromIterator` for your type:
60 /// use std::iter::FromIterator;
62 /// // A sample collection, that's just a wrapper over Vec<T>
64 /// struct MyCollection(Vec<i32>);
66 /// // Let's give it some methods so we can create one and add things
68 /// impl MyCollection {
69 /// fn new() -> MyCollection {
70 /// MyCollection(Vec::new())
73 /// fn add(&mut self, elem: i32) {
74 /// self.0.push(elem);
78 /// // and we'll implement FromIterator
79 /// impl FromIterator<i32> for MyCollection {
80 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
81 /// let mut c = MyCollection::new();
91 /// // Now we can make a new iterator...
92 /// let iter = (0..5).into_iter();
94 /// // ... and make a MyCollection out of it
95 /// let c = MyCollection::from_iter(iter);
97 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
99 /// // collect works too!
101 /// let iter = (0..5).into_iter();
102 /// let c: MyCollection = iter.collect();
104 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
106 #[stable(feature = "rust1", since = "1.0.0")]
107 #[rustc_on_unimplemented(
108 message="a collection of type `{Self}` cannot be built from an iterator \
109 over elements of type `{A}`",
110 label="a collection of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`",
112 pub trait FromIterator<A>: Sized {
113 /// Creates a value from an iterator.
115 /// See the [module-level documentation] for more.
117 /// [module-level documentation]: index.html
124 /// use std::iter::FromIterator;
126 /// let five_fives = std::iter::repeat(5).take(5);
128 /// let v = Vec::from_iter(five_fives);
130 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
132 #[stable(feature = "rust1", since = "1.0.0")]
133 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
136 /// Conversion into an `Iterator`.
138 /// By implementing `IntoIterator` for a type, you define how it will be
139 /// converted to an iterator. This is common for types which describe a
140 /// collection of some kind.
142 /// One benefit of implementing `IntoIterator` is that your type will [work
143 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
145 /// See also: [`FromIterator`].
147 /// [`FromIterator`]: trait.FromIterator.html
154 /// let v = vec![1, 2, 3];
155 /// let mut iter = v.into_iter();
157 /// assert_eq!(Some(1), iter.next());
158 /// assert_eq!(Some(2), iter.next());
159 /// assert_eq!(Some(3), iter.next());
160 /// assert_eq!(None, iter.next());
162 /// Implementing `IntoIterator` for your type:
165 /// // A sample collection, that's just a wrapper over Vec<T>
167 /// struct MyCollection(Vec<i32>);
169 /// // Let's give it some methods so we can create one and add things
171 /// impl MyCollection {
172 /// fn new() -> MyCollection {
173 /// MyCollection(Vec::new())
176 /// fn add(&mut self, elem: i32) {
177 /// self.0.push(elem);
181 /// // and we'll implement IntoIterator
182 /// impl IntoIterator for MyCollection {
184 /// type IntoIter = ::std::vec::IntoIter<i32>;
186 /// fn into_iter(self) -> Self::IntoIter {
187 /// self.0.into_iter()
191 /// // Now we can make a new collection...
192 /// let mut c = MyCollection::new();
194 /// // ... add some stuff to it ...
199 /// // ... and then turn it into an Iterator:
200 /// for (i, n) in c.into_iter().enumerate() {
201 /// assert_eq!(i as i32, n);
205 /// It is common to use `IntoIterator` as a trait bound. This allows
206 /// the input collection type to change, so long as it is still an
207 /// iterator. Additional bounds can be specified by restricting on
211 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
212 /// where T: IntoIterator,
213 /// T::Item : std::fmt::Debug,
217 /// .map(|item| format!("{:?}", item))
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub trait IntoIterator {
223 /// The type of the elements being iterated over.
224 #[stable(feature = "rust1", since = "1.0.0")]
227 /// Which kind of iterator are we turning this into?
228 #[stable(feature = "rust1", since = "1.0.0")]
229 type IntoIter: Iterator<Item=Self::Item>;
231 /// Creates an iterator from a value.
233 /// See the [module-level documentation] for more.
235 /// [module-level documentation]: index.html
242 /// let v = vec![1, 2, 3];
243 /// let mut iter = v.into_iter();
245 /// assert_eq!(Some(1), iter.next());
246 /// assert_eq!(Some(2), iter.next());
247 /// assert_eq!(Some(3), iter.next());
248 /// assert_eq!(None, iter.next());
250 #[stable(feature = "rust1", since = "1.0.0")]
251 fn into_iter(self) -> Self::IntoIter;
254 #[stable(feature = "rust1", since = "1.0.0")]
255 impl<I: Iterator> IntoIterator for I {
259 fn into_iter(self) -> I {
264 /// Extend a collection with the contents of an iterator.
266 /// Iterators produce a series of values, and collections can also be thought
267 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
268 /// to extend a collection by including the contents of that iterator. When
269 /// extending a collection with an already existing key, that entry is updated
270 /// or, in the case of collections that permit multiple entries with equal
271 /// keys, that entry is inserted.
278 /// // You can extend a String with some chars:
279 /// let mut message = String::from("The first three letters are: ");
281 /// message.extend(&['a', 'b', 'c']);
283 /// assert_eq!("abc", &message[29..32]);
286 /// Implementing `Extend`:
289 /// // A sample collection, that's just a wrapper over Vec<T>
291 /// struct MyCollection(Vec<i32>);
293 /// // Let's give it some methods so we can create one and add things
295 /// impl MyCollection {
296 /// fn new() -> MyCollection {
297 /// MyCollection(Vec::new())
300 /// fn add(&mut self, elem: i32) {
301 /// self.0.push(elem);
305 /// // since MyCollection has a list of i32s, we implement Extend for i32
306 /// impl Extend<i32> for MyCollection {
308 /// // This is a bit simpler with the concrete type signature: we can call
309 /// // extend on anything which can be turned into an Iterator which gives
310 /// // us i32s. Because we need i32s to put into MyCollection.
311 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
313 /// // The implementation is very straightforward: loop through the
314 /// // iterator, and add() each element to ourselves.
315 /// for elem in iter {
321 /// let mut c = MyCollection::new();
327 /// // let's extend our collection with three more numbers
328 /// c.extend(vec![1, 2, 3]);
330 /// // we've added these elements onto the end
331 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub trait Extend<A> {
335 /// Extends a collection with the contents of an iterator.
337 /// As this is the only method for this trait, the [trait-level] docs
338 /// contain more details.
340 /// [trait-level]: trait.Extend.html
347 /// // You can extend a String with some chars:
348 /// let mut message = String::from("abc");
350 /// message.extend(['d', 'e', 'f'].iter());
352 /// assert_eq!("abcdef", &message);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
358 #[stable(feature = "extend_for_unit", since = "1.28.0")]
359 impl Extend<()> for () {
360 fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
361 iter.into_iter().for_each(drop)
365 /// An iterator able to yield elements from both ends.
367 /// Something that implements `DoubleEndedIterator` has one extra capability
368 /// over something that implements [`Iterator`]: the ability to also take
369 /// `Item`s from the back, as well as the front.
371 /// It is important to note that both back and forth work on the same range,
372 /// and do not cross: iteration is over when they meet in the middle.
374 /// In a similar fashion to the [`Iterator`] protocol, once a
375 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
376 /// may or may not ever return `Some` again. `next()` and `next_back()` are
377 /// interchangeable for this purpose.
379 /// [`Iterator`]: trait.Iterator.html
386 /// let numbers = vec![1, 2, 3, 4, 5, 6];
388 /// let mut iter = numbers.iter();
390 /// assert_eq!(Some(&1), iter.next());
391 /// assert_eq!(Some(&6), iter.next_back());
392 /// assert_eq!(Some(&5), iter.next_back());
393 /// assert_eq!(Some(&2), iter.next());
394 /// assert_eq!(Some(&3), iter.next());
395 /// assert_eq!(Some(&4), iter.next());
396 /// assert_eq!(None, iter.next());
397 /// assert_eq!(None, iter.next_back());
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub trait DoubleEndedIterator: Iterator {
401 /// Removes and returns an element from the end of the iterator.
403 /// Returns `None` when there are no more elements.
405 /// The [trait-level] docs contain more details.
407 /// [trait-level]: trait.DoubleEndedIterator.html
414 /// let numbers = vec![1, 2, 3, 4, 5, 6];
416 /// let mut iter = numbers.iter();
418 /// assert_eq!(Some(&1), iter.next());
419 /// assert_eq!(Some(&6), iter.next_back());
420 /// assert_eq!(Some(&5), iter.next_back());
421 /// assert_eq!(Some(&2), iter.next());
422 /// assert_eq!(Some(&3), iter.next());
423 /// assert_eq!(Some(&4), iter.next());
424 /// assert_eq!(None, iter.next());
425 /// assert_eq!(None, iter.next_back());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 fn next_back(&mut self) -> Option<Self::Item>;
430 /// Returns the `n`th element from the end of the iterator.
432 /// This is essentially the reversed version of [`nth`]. Although like most indexing
433 /// operations, the count starts from zero, so `nth_back(0)` returns the first value fro
434 /// the end, `nth_back(1)` the second, and so on.
436 /// Note that all elements between the end and the returned element will be
437 /// consumed, including the returned element. This also means that calling
438 /// `nth_back(0)` multiple times on the same iterator will return different
441 /// `nth_back()` will return [`None`] if `n` is greater than or equal to the length of the
444 /// [`None`]: ../../std/option/enum.Option.html#variant.None
445 /// [`nth`]: ../../std/iter/trait.Iterator.html#method.nth
452 /// #![feature(iter_nth_back)]
453 /// let a = [1, 2, 3];
454 /// assert_eq!(a.iter().nth_back(2), Some(&1));
457 /// Calling `nth_back()` multiple times doesn't rewind the iterator:
460 /// #![feature(iter_nth_back)]
461 /// let a = [1, 2, 3];
463 /// let mut iter = a.iter();
465 /// assert_eq!(iter.nth_back(1), Some(&2));
466 /// assert_eq!(iter.nth_back(1), None);
469 /// Returning `None` if there are less than `n + 1` elements:
472 /// #![feature(iter_nth_back)]
473 /// let a = [1, 2, 3];
474 /// assert_eq!(a.iter().nth_back(10), None);
477 #[unstable(feature = "iter_nth_back", issue = "56995")]
478 fn nth_back(&mut self, mut n: usize) -> Option<Self::Item> {
479 for x in self.rev() {
480 if n == 0 { return Some(x) }
486 /// This is the reverse version of [`try_fold()`]: it takes elements
487 /// starting from the back of the iterator.
489 /// [`try_fold()`]: trait.Iterator.html#method.try_fold
496 /// let a = ["1", "2", "3"];
497 /// let sum = a.iter()
498 /// .map(|&s| s.parse::<i32>())
499 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
500 /// assert_eq!(sum, Ok(6));
503 /// Short-circuiting:
506 /// let a = ["1", "rust", "3"];
507 /// let mut it = a.iter();
510 /// .map(|&s| s.parse::<i32>())
511 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
512 /// assert!(sum.is_err());
514 /// // Because it short-circuited, the remaining elements are still
515 /// // available through the iterator.
516 /// assert_eq!(it.next_back(), Some(&"1"));
519 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
520 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
523 F: FnMut(B, Self::Item) -> R,
526 let mut accum = init;
527 while let Some(x) = self.next_back() {
528 accum = f(accum, x)?;
533 /// An iterator method that reduces the iterator's elements to a single,
534 /// final value, starting from the back.
536 /// This is the reverse version of [`fold()`]: it takes elements starting from
537 /// the back of the iterator.
539 /// `rfold()` takes two arguments: an initial value, and a closure with two
540 /// arguments: an 'accumulator', and an element. The closure returns the value that
541 /// the accumulator should have for the next iteration.
543 /// The initial value is the value the accumulator will have on the first
546 /// After applying this closure to every element of the iterator, `rfold()`
547 /// returns the accumulator.
549 /// This operation is sometimes called 'reduce' or 'inject'.
551 /// Folding is useful whenever you have a collection of something, and want
552 /// to produce a single value from it.
554 /// [`fold()`]: trait.Iterator.html#method.fold
561 /// let a = [1, 2, 3];
563 /// // the sum of all of the elements of a
564 /// let sum = a.iter()
565 /// .rfold(0, |acc, &x| acc + x);
567 /// assert_eq!(sum, 6);
570 /// This example builds a string, starting with an initial value
571 /// and continuing with each element from the back until the front:
574 /// let numbers = [1, 2, 3, 4, 5];
576 /// let zero = "0".to_string();
578 /// let result = numbers.iter().rfold(zero, |acc, &x| {
579 /// format!("({} + {})", x, acc)
582 /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
585 #[stable(feature = "iter_rfold", since = "1.27.0")]
586 fn rfold<B, F>(mut self, accum: B, mut f: F) -> B
589 F: FnMut(B, Self::Item) -> B,
591 self.try_rfold(accum, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
594 /// Searches for an element of an iterator from the back that satisfies a predicate.
596 /// `rfind()` takes a closure that returns `true` or `false`. It applies
597 /// this closure to each element of the iterator, starting at the end, and if any
598 /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
599 /// `false`, it returns [`None`].
601 /// `rfind()` is short-circuiting; in other words, it will stop processing
602 /// as soon as the closure returns `true`.
604 /// Because `rfind()` takes a reference, and many iterators iterate over
605 /// references, this leads to a possibly confusing situation where the
606 /// argument is a double reference. You can see this effect in the
607 /// examples below, with `&&x`.
609 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
610 /// [`None`]: ../../std/option/enum.Option.html#variant.None
617 /// let a = [1, 2, 3];
619 /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
621 /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
624 /// Stopping at the first `true`:
627 /// let a = [1, 2, 3];
629 /// let mut iter = a.iter();
631 /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
633 /// // we can still use `iter`, as there are more elements.
634 /// assert_eq!(iter.next_back(), Some(&1));
637 #[stable(feature = "iter_rfind", since = "1.27.0")]
638 fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item>
641 P: FnMut(&Self::Item) -> bool
643 self.try_rfold((), move |(), x| {
644 if predicate(&x) { LoopState::Break(x) }
645 else { LoopState::Continue(()) }
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
652 fn next_back(&mut self) -> Option<I::Item> {
655 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
660 /// An iterator that knows its exact length.
662 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
663 /// If an iterator knows how many times it can iterate, providing access to
664 /// that information can be useful. For example, if you want to iterate
665 /// backwards, a good start is to know where the end is.
667 /// When implementing an `ExactSizeIterator`, you must also implement
668 /// [`Iterator`]. When doing so, the implementation of [`size_hint`] *must*
669 /// return the exact size of the iterator.
671 /// [`Iterator`]: trait.Iterator.html
672 /// [`size_hint`]: trait.Iterator.html#method.size_hint
674 /// The [`len`] method has a default implementation, so you usually shouldn't
675 /// implement it. However, you may be able to provide a more performant
676 /// implementation than the default, so overriding it in this case makes sense.
678 /// [`len`]: #method.len
685 /// // a finite range knows exactly how many times it will iterate
688 /// assert_eq!(5, five.len());
691 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
692 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
694 /// [moddocs]: index.html
697 /// # struct Counter {
701 /// # fn new() -> Counter {
702 /// # Counter { count: 0 }
705 /// # impl Iterator for Counter {
706 /// # type Item = usize;
707 /// # fn next(&mut self) -> Option<usize> {
708 /// # self.count += 1;
709 /// # if self.count < 6 {
710 /// # Some(self.count)
716 /// impl ExactSizeIterator for Counter {
717 /// // We can easily calculate the remaining number of iterations.
718 /// fn len(&self) -> usize {
723 /// // And now we can use it!
725 /// let counter = Counter::new();
727 /// assert_eq!(5, counter.len());
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub trait ExactSizeIterator: Iterator {
731 /// Returns the exact number of times the iterator will iterate.
733 /// This method has a default implementation, so you usually should not
734 /// implement it directly. However, if you can provide a more efficient
735 /// implementation, you can do so. See the [trait-level] docs for an
738 /// This function has the same safety guarantees as the [`size_hint`]
741 /// [trait-level]: trait.ExactSizeIterator.html
742 /// [`size_hint`]: trait.Iterator.html#method.size_hint
749 /// // a finite range knows exactly how many times it will iterate
752 /// assert_eq!(5, five.len());
755 #[stable(feature = "rust1", since = "1.0.0")]
756 fn len(&self) -> usize {
757 let (lower, upper) = self.size_hint();
758 // Note: This assertion is overly defensive, but it checks the invariant
759 // guaranteed by the trait. If this trait were rust-internal,
760 // we could use debug_assert!; assert_eq! will check all Rust user
761 // implementations too.
762 assert_eq!(upper, Some(lower));
766 /// Returns whether the iterator is empty.
768 /// This method has a default implementation using `self.len()`, so you
769 /// don't need to implement it yourself.
776 /// #![feature(exact_size_is_empty)]
778 /// let mut one_element = std::iter::once(0);
779 /// assert!(!one_element.is_empty());
781 /// assert_eq!(one_element.next(), Some(0));
782 /// assert!(one_element.is_empty());
784 /// assert_eq!(one_element.next(), None);
787 #[unstable(feature = "exact_size_is_empty", issue = "35428")]
788 fn is_empty(&self) -> bool {
793 #[stable(feature = "rust1", since = "1.0.0")]
794 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for &mut I {
795 fn len(&self) -> usize {
798 fn is_empty(&self) -> bool {
803 /// Trait to represent types that can be created by summing up an iterator.
805 /// This trait is used to implement the [`sum`] method on iterators. Types which
806 /// implement the trait can be generated by the [`sum`] method. Like
807 /// [`FromIterator`] this trait should rarely be called directly and instead
808 /// interacted with through [`Iterator::sum`].
810 /// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum
811 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
812 /// [`Iterator::sum`]: ../../std/iter/trait.Iterator.html#method.sum
813 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
814 pub trait Sum<A = Self>: Sized {
815 /// Method which takes an iterator and generates `Self` from the elements by
816 /// "summing up" the items.
817 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
818 fn sum<I: Iterator<Item=A>>(iter: I) -> Self;
821 /// Trait to represent types that can be created by multiplying elements of an
824 /// This trait is used to implement the [`product`] method on iterators. Types
825 /// which implement the trait can be generated by the [`product`] method. Like
826 /// [`FromIterator`] this trait should rarely be called directly and instead
827 /// interacted with through [`Iterator::product`].
829 /// [`product`]: ../../std/iter/trait.Product.html#tymethod.product
830 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
831 /// [`Iterator::product`]: ../../std/iter/trait.Iterator.html#method.product
832 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
833 pub trait Product<A = Self>: Sized {
834 /// Method which takes an iterator and generates `Self` from the elements by
835 /// multiplying the items.
836 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
837 fn product<I: Iterator<Item=A>>(iter: I) -> Self;
840 // N.B., explicitly use Add and Mul here to inherit overflow checks
841 macro_rules! integer_sum_product {
842 (@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
845 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
846 iter.fold($zero, Add::add)
851 impl Product for $a {
852 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
853 iter.fold($one, Mul::mul)
858 impl<'a> Sum<&'a $a> for $a {
859 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
860 iter.fold($zero, Add::add)
865 impl<'a> Product<&'a $a> for $a {
866 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
867 iter.fold($one, Mul::mul)
872 integer_sum_product!(@impls 0, 1,
873 #[stable(feature = "iter_arith_traits", since = "1.12.0")],
875 integer_sum_product!(@impls Wrapping(0), Wrapping(1),
876 #[stable(feature = "wrapping_iter_arith", since = "1.14.0")],
881 macro_rules! float_sum_product {
882 ($($a:ident)*) => ($(
883 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
885 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
886 iter.fold(0.0, |a, b| a + b)
890 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
891 impl Product for $a {
892 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
893 iter.fold(1.0, |a, b| a * b)
897 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
898 impl<'a> Sum<&'a $a> for $a {
899 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
900 iter.fold(0.0, |a, b| a + *b)
904 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
905 impl<'a> Product<&'a $a> for $a {
906 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
907 iter.fold(1.0, |a, b| a * *b)
913 integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
914 float_sum_product! { f32 f64 }
916 /// An iterator adapter that produces output as long as the underlying
917 /// iterator produces `Result::Ok` values.
919 /// If an error is encountered, the iterator stops and the error is
920 /// stored. The error may be recovered later via `reconstruct`.
921 struct ResultShunt<I, E> {
926 impl<I, T, E> ResultShunt<I, E>
927 where I: Iterator<Item = Result<T, E>>
929 /// Process the given iterator as if it yielded a `T` instead of a
930 /// `Result<T, _>`. Any errors will stop the inner iterator and
931 /// the overall result will be an error.
932 pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
933 where F: FnMut(&mut Self) -> U
935 let mut shunt = ResultShunt::new(iter);
936 let value = f(shunt.by_ref());
937 shunt.reconstruct(value)
940 fn new(iter: I) -> Self {
947 /// Consume the adapter and rebuild a `Result` value. This should
948 /// *always* be called, otherwise any potential error would be
950 fn reconstruct<U>(self, val: U) -> Result<U, E> {
958 impl<I, T, E> Iterator for ResultShunt<I, E>
959 where I: Iterator<Item = Result<T, E>>
963 fn next(&mut self) -> Option<Self::Item> {
964 match self.iter.next() {
965 Some(Ok(v)) => Some(v),
967 self.error = Some(e);
974 fn size_hint(&self) -> (usize, Option<usize>) {
975 if self.error.is_some() {
978 let (_, upper) = self.iter.size_hint();
984 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
985 impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
988 /// Takes each element in the `Iterator`: if it is an `Err`, no further
989 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
990 /// the sum of all elements is returned.
994 /// This sums up every integer in a vector, rejecting the sum if a negative
995 /// element is encountered:
998 /// let v = vec![1, 2];
999 /// let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
1000 /// if x < 0 { Err("Negative element found") }
1003 /// assert_eq!(res, Ok(3));
1005 fn sum<I>(iter: I) -> Result<T, E>
1006 where I: Iterator<Item = Result<U, E>>,
1008 ResultShunt::process(iter, |i| i.sum())
1012 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
1013 impl<T, U, E> Product<Result<U, E>> for Result<T, E>
1014 where T: Product<U>,
1016 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1017 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
1018 /// the product of all elements is returned.
1019 fn product<I>(iter: I) -> Result<T, E>
1020 where I: Iterator<Item = Result<U, E>>,
1022 ResultShunt::process(iter, |i| i.product())
1026 /// An iterator that always continues to yield `None` when exhausted.
1028 /// Calling next on a fused iterator that has returned `None` once is guaranteed
1029 /// to return [`None`] again. This trait should be implemented by all iterators
1030 /// that behave this way because it allows optimizing [`Iterator::fuse`].
1032 /// Note: In general, you should not use `FusedIterator` in generic bounds if
1033 /// you need a fused iterator. Instead, you should just call [`Iterator::fuse`]
1034 /// on the iterator. If the iterator is already fused, the additional [`Fuse`]
1035 /// wrapper will be a no-op with no performance penalty.
1037 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1038 /// [`Iterator::fuse`]: ../../std/iter/trait.Iterator.html#method.fuse
1039 /// [`Fuse`]: ../../std/iter/struct.Fuse.html
1040 #[stable(feature = "fused", since = "1.26.0")]
1041 pub trait FusedIterator: Iterator {}
1043 #[stable(feature = "fused", since = "1.26.0")]
1044 impl<I: FusedIterator + ?Sized> FusedIterator for &mut I {}
1046 /// An iterator that reports an accurate length using size_hint.
1048 /// The iterator reports a size hint where it is either exact
1049 /// (lower bound is equal to upper bound), or the upper bound is [`None`].
1050 /// The upper bound must only be [`None`] if the actual iterator length is
1051 /// larger than [`usize::MAX`]. In that case, the lower bound must be
1052 /// [`usize::MAX`], resulting in a [`.size_hint`] of `(usize::MAX, None)`.
1054 /// The iterator must produce exactly the number of elements it reported
1055 /// or diverge before reaching the end.
1059 /// This trait must only be implemented when the contract is upheld.
1060 /// Consumers of this trait must inspect [`.size_hint`]’s upper bound.
1062 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1063 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1064 /// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint
1065 #[unstable(feature = "trusted_len", issue = "37572")]
1066 pub unsafe trait TrustedLen : Iterator {}
1068 #[unstable(feature = "trusted_len", issue = "37572")]
1069 unsafe impl<I: TrustedLen + ?Sized> TrustedLen for &mut I {}