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 /// This is the reverse version of [`try_fold()`]: it takes elements
431 /// starting from the back of the iterator.
433 /// [`try_fold()`]: trait.Iterator.html#method.try_fold
440 /// let a = ["1", "2", "3"];
441 /// let sum = a.iter()
442 /// .map(|&s| s.parse::<i32>())
443 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
444 /// assert_eq!(sum, Ok(6));
447 /// Short-circuiting:
450 /// let a = ["1", "rust", "3"];
451 /// let mut it = a.iter();
454 /// .map(|&s| s.parse::<i32>())
455 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
456 /// assert!(sum.is_err());
458 /// // Because it short-circuited, the remaining elements are still
459 /// // available through the iterator.
460 /// assert_eq!(it.next_back(), Some(&"1"));
463 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
464 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
465 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
467 let mut accum = init;
468 while let Some(x) = self.next_back() {
469 accum = f(accum, x)?;
474 /// An iterator method that reduces the iterator's elements to a single,
475 /// final value, starting from the back.
477 /// This is the reverse version of [`fold()`]: it takes elements starting from
478 /// the back of the iterator.
480 /// `rfold()` takes two arguments: an initial value, and a closure with two
481 /// arguments: an 'accumulator', and an element. The closure returns the value that
482 /// the accumulator should have for the next iteration.
484 /// The initial value is the value the accumulator will have on the first
487 /// After applying this closure to every element of the iterator, `rfold()`
488 /// returns the accumulator.
490 /// This operation is sometimes called 'reduce' or 'inject'.
492 /// Folding is useful whenever you have a collection of something, and want
493 /// to produce a single value from it.
495 /// [`fold()`]: trait.Iterator.html#method.fold
502 /// let a = [1, 2, 3];
504 /// // the sum of all of the elements of a
505 /// let sum = a.iter()
506 /// .rfold(0, |acc, &x| acc + x);
508 /// assert_eq!(sum, 6);
511 /// This example builds a string, starting with an initial value
512 /// and continuing with each element from the back until the front:
515 /// let numbers = [1, 2, 3, 4, 5];
517 /// let zero = "0".to_string();
519 /// let result = numbers.iter().rfold(zero, |acc, &x| {
520 /// format!("({} + {})", x, acc)
523 /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
526 #[stable(feature = "iter_rfold", since = "1.27.0")]
527 fn rfold<B, F>(mut self, accum: B, mut f: F) -> B where
528 Self: Sized, F: FnMut(B, Self::Item) -> B,
530 self.try_rfold(accum, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
533 /// Searches for an element of an iterator from the back that satisfies a predicate.
535 /// `rfind()` takes a closure that returns `true` or `false`. It applies
536 /// this closure to each element of the iterator, starting at the end, and if any
537 /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
538 /// `false`, it returns [`None`].
540 /// `rfind()` is short-circuiting; in other words, it will stop processing
541 /// as soon as the closure returns `true`.
543 /// Because `rfind()` takes a reference, and many iterators iterate over
544 /// references, this leads to a possibly confusing situation where the
545 /// argument is a double reference. You can see this effect in the
546 /// examples below, with `&&x`.
548 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
549 /// [`None`]: ../../std/option/enum.Option.html#variant.None
556 /// let a = [1, 2, 3];
558 /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
560 /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
563 /// Stopping at the first `true`:
566 /// let a = [1, 2, 3];
568 /// let mut iter = a.iter();
570 /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
572 /// // we can still use `iter`, as there are more elements.
573 /// assert_eq!(iter.next_back(), Some(&1));
576 #[stable(feature = "iter_rfind", since = "1.27.0")]
577 fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
579 P: FnMut(&Self::Item) -> bool
581 self.try_rfold((), move |(), x| {
582 if predicate(&x) { LoopState::Break(x) }
583 else { LoopState::Continue(()) }
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
590 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
593 /// An iterator that knows its exact length.
595 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
596 /// If an iterator knows how many times it can iterate, providing access to
597 /// that information can be useful. For example, if you want to iterate
598 /// backwards, a good start is to know where the end is.
600 /// When implementing an `ExactSizeIterator`, you must also implement
601 /// [`Iterator`]. When doing so, the implementation of [`size_hint`] *must*
602 /// return the exact size of the iterator.
604 /// [`Iterator`]: trait.Iterator.html
605 /// [`size_hint`]: trait.Iterator.html#method.size_hint
607 /// The [`len`] method has a default implementation, so you usually shouldn't
608 /// implement it. However, you may be able to provide a more performant
609 /// implementation than the default, so overriding it in this case makes sense.
611 /// [`len`]: #method.len
618 /// // a finite range knows exactly how many times it will iterate
621 /// assert_eq!(5, five.len());
624 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
625 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
627 /// [moddocs]: index.html
630 /// # struct Counter {
634 /// # fn new() -> Counter {
635 /// # Counter { count: 0 }
638 /// # impl Iterator for Counter {
639 /// # type Item = usize;
640 /// # fn next(&mut self) -> Option<usize> {
641 /// # self.count += 1;
642 /// # if self.count < 6 {
643 /// # Some(self.count)
649 /// impl ExactSizeIterator for Counter {
650 /// // We can easily calculate the remaining number of iterations.
651 /// fn len(&self) -> usize {
656 /// // And now we can use it!
658 /// let counter = Counter::new();
660 /// assert_eq!(5, counter.len());
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub trait ExactSizeIterator: Iterator {
664 /// Returns the exact number of times the iterator will iterate.
666 /// This method has a default implementation, so you usually should not
667 /// implement it directly. However, if you can provide a more efficient
668 /// implementation, you can do so. See the [trait-level] docs for an
671 /// This function has the same safety guarantees as the [`size_hint`]
674 /// [trait-level]: trait.ExactSizeIterator.html
675 /// [`size_hint`]: trait.Iterator.html#method.size_hint
682 /// // a finite range knows exactly how many times it will iterate
685 /// assert_eq!(5, five.len());
688 #[stable(feature = "rust1", since = "1.0.0")]
689 fn len(&self) -> usize {
690 let (lower, upper) = self.size_hint();
691 // Note: This assertion is overly defensive, but it checks the invariant
692 // guaranteed by the trait. If this trait were rust-internal,
693 // we could use debug_assert!; assert_eq! will check all Rust user
694 // implementations too.
695 assert_eq!(upper, Some(lower));
699 /// Returns whether the iterator is empty.
701 /// This method has a default implementation using `self.len()`, so you
702 /// don't need to implement it yourself.
709 /// #![feature(exact_size_is_empty)]
711 /// let mut one_element = std::iter::once(0);
712 /// assert!(!one_element.is_empty());
714 /// assert_eq!(one_element.next(), Some(0));
715 /// assert!(one_element.is_empty());
717 /// assert_eq!(one_element.next(), None);
720 #[unstable(feature = "exact_size_is_empty", issue = "35428")]
721 fn is_empty(&self) -> bool {
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for &mut I {
728 fn len(&self) -> usize {
731 fn is_empty(&self) -> bool {
736 /// Trait to represent types that can be created by summing up an iterator.
738 /// This trait is used to implement the [`sum`] method on iterators. Types which
739 /// implement the trait can be generated by the [`sum`] method. Like
740 /// [`FromIterator`] this trait should rarely be called directly and instead
741 /// interacted with through [`Iterator::sum`].
743 /// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum
744 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
745 /// [`Iterator::sum`]: ../../std/iter/trait.Iterator.html#method.sum
746 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
747 pub trait Sum<A = Self>: Sized {
748 /// Method which takes an iterator and generates `Self` from the elements by
749 /// "summing up" the items.
750 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
751 fn sum<I: Iterator<Item=A>>(iter: I) -> Self;
754 /// Trait to represent types that can be created by multiplying elements of an
757 /// This trait is used to implement the [`product`] method on iterators. Types
758 /// which implement the trait can be generated by the [`product`] method. Like
759 /// [`FromIterator`] this trait should rarely be called directly and instead
760 /// interacted with through [`Iterator::product`].
762 /// [`product`]: ../../std/iter/trait.Product.html#tymethod.product
763 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
764 /// [`Iterator::product`]: ../../std/iter/trait.Iterator.html#method.product
765 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
766 pub trait Product<A = Self>: Sized {
767 /// Method which takes an iterator and generates `Self` from the elements by
768 /// multiplying the items.
769 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
770 fn product<I: Iterator<Item=A>>(iter: I) -> Self;
773 // N.B., explicitly use Add and Mul here to inherit overflow checks
774 macro_rules! integer_sum_product {
775 (@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
778 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
779 iter.fold($zero, Add::add)
784 impl Product for $a {
785 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
786 iter.fold($one, Mul::mul)
791 impl<'a> Sum<&'a $a> for $a {
792 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
793 iter.fold($zero, Add::add)
798 impl<'a> Product<&'a $a> for $a {
799 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
800 iter.fold($one, Mul::mul)
805 integer_sum_product!(@impls 0, 1,
806 #[stable(feature = "iter_arith_traits", since = "1.12.0")],
808 integer_sum_product!(@impls Wrapping(0), Wrapping(1),
809 #[stable(feature = "wrapping_iter_arith", since = "1.14.0")],
814 macro_rules! float_sum_product {
815 ($($a:ident)*) => ($(
816 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
818 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
819 iter.fold(0.0, |a, b| a + b)
823 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
824 impl Product for $a {
825 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
826 iter.fold(1.0, |a, b| a * b)
830 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
831 impl<'a> Sum<&'a $a> for $a {
832 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
833 iter.fold(0.0, |a, b| a + *b)
837 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
838 impl<'a> Product<&'a $a> for $a {
839 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
840 iter.fold(1.0, |a, b| a * *b)
846 integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
847 float_sum_product! { f32 f64 }
849 /// An iterator adapter that produces output as long as the underlying
850 /// iterator produces `Result::Ok` values.
852 /// If an error is encountered, the iterator stops and the error is
853 /// stored. The error may be recovered later via `reconstruct`.
854 struct ResultShunt<I, E> {
859 impl<I, T, E> ResultShunt<I, E>
860 where I: Iterator<Item = Result<T, E>>
862 /// Process the given iterator as if it yielded a `T` instead of a
863 /// `Result<T, _>`. Any errors will stop the inner iterator and
864 /// the overall result will be an error.
865 pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
866 where F: FnMut(&mut Self) -> U
868 let mut shunt = ResultShunt::new(iter);
869 let value = f(shunt.by_ref());
870 shunt.reconstruct(value)
873 fn new(iter: I) -> Self {
880 /// Consume the adapter and rebuild a `Result` value. This should
881 /// *always* be called, otherwise any potential error would be
883 fn reconstruct<U>(self, val: U) -> Result<U, E> {
891 impl<I, T, E> Iterator for ResultShunt<I, E>
892 where I: Iterator<Item = Result<T, E>>
896 fn next(&mut self) -> Option<Self::Item> {
897 match self.iter.next() {
898 Some(Ok(v)) => Some(v),
900 self.error = Some(e);
907 fn size_hint(&self) -> (usize, Option<usize>) {
908 if self.error.is_some() {
911 let (_, upper) = self.iter.size_hint();
917 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
918 impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
921 /// Takes each element in the `Iterator`: if it is an `Err`, no further
922 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
923 /// the sum of all elements is returned.
927 /// This sums up every integer in a vector, rejecting the sum if a negative
928 /// element is encountered:
931 /// let v = vec![1, 2];
932 /// let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
933 /// if x < 0 { Err("Negative element found") }
936 /// assert_eq!(res, Ok(3));
938 fn sum<I>(iter: I) -> Result<T, E>
939 where I: Iterator<Item = Result<U, E>>,
941 ResultShunt::process(iter, |i| i.sum())
945 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
946 impl<T, U, E> Product<Result<U, E>> for Result<T, E>
949 /// Takes each element in the `Iterator`: if it is an `Err`, no further
950 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
951 /// the product of all elements is returned.
952 fn product<I>(iter: I) -> Result<T, E>
953 where I: Iterator<Item = Result<U, E>>,
955 ResultShunt::process(iter, |i| i.product())
959 /// An iterator that always continues to yield `None` when exhausted.
961 /// Calling next on a fused iterator that has returned `None` once is guaranteed
962 /// to return [`None`] again. This trait should be implemented by all iterators
963 /// that behave this way because it allows optimizing [`Iterator::fuse`].
965 /// Note: In general, you should not use `FusedIterator` in generic bounds if
966 /// you need a fused iterator. Instead, you should just call [`Iterator::fuse`]
967 /// on the iterator. If the iterator is already fused, the additional [`Fuse`]
968 /// wrapper will be a no-op with no performance penalty.
970 /// [`None`]: ../../std/option/enum.Option.html#variant.None
971 /// [`Iterator::fuse`]: ../../std/iter/trait.Iterator.html#method.fuse
972 /// [`Fuse`]: ../../std/iter/struct.Fuse.html
973 #[stable(feature = "fused", since = "1.26.0")]
974 pub trait FusedIterator: Iterator {}
976 #[stable(feature = "fused", since = "1.26.0")]
977 impl<I: FusedIterator + ?Sized> FusedIterator for &mut I {}
979 /// An iterator that reports an accurate length using size_hint.
981 /// The iterator reports a size hint where it is either exact
982 /// (lower bound is equal to upper bound), or the upper bound is [`None`].
983 /// The upper bound must only be [`None`] if the actual iterator length is
984 /// larger than [`usize::MAX`]. In that case, the lower bound must be
985 /// [`usize::MAX`], resulting in a [`.size_hint`] of `(usize::MAX, None)`.
987 /// The iterator must produce exactly the number of elements it reported
988 /// or diverge before reaching the end.
992 /// This trait must only be implemented when the contract is upheld.
993 /// Consumers of this trait must inspect [`.size_hint`]’s upper bound.
995 /// [`None`]: ../../std/option/enum.Option.html#variant.None
996 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
997 /// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint
998 #[unstable(feature = "trusted_len", issue = "37572")]
999 pub unsafe trait TrustedLen : Iterator {}
1001 #[unstable(feature = "trusted_len", issue = "37572")]
1002 unsafe impl<I: TrustedLen + ?Sized> TrustedLen for &mut I {}