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};
13 use super::{AlwaysOk, LoopState};
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="a collection of type `{Self}` cannot be \
108 built from an iterator over elements of type `{A}`"]
109 pub trait FromIterator<A>: Sized {
110 /// Creates a value from an iterator.
112 /// See the [module-level documentation] for more.
114 /// [module-level documentation]: index.html
121 /// use std::iter::FromIterator;
123 /// let five_fives = std::iter::repeat(5).take(5);
125 /// let v = Vec::from_iter(five_fives);
127 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
129 #[stable(feature = "rust1", since = "1.0.0")]
130 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
133 /// Conversion into an `Iterator`.
135 /// By implementing `IntoIterator` for a type, you define how it will be
136 /// converted to an iterator. This is common for types which describe a
137 /// collection of some kind.
139 /// One benefit of implementing `IntoIterator` is that your type will [work
140 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
142 /// See also: [`FromIterator`].
144 /// [`FromIterator`]: trait.FromIterator.html
151 /// let v = vec![1, 2, 3];
152 /// let mut iter = v.into_iter();
154 /// assert_eq!(Some(1), iter.next());
155 /// assert_eq!(Some(2), iter.next());
156 /// assert_eq!(Some(3), iter.next());
157 /// assert_eq!(None, iter.next());
159 /// Implementing `IntoIterator` for your type:
162 /// // A sample collection, that's just a wrapper over Vec<T>
164 /// struct MyCollection(Vec<i32>);
166 /// // Let's give it some methods so we can create one and add things
168 /// impl MyCollection {
169 /// fn new() -> MyCollection {
170 /// MyCollection(Vec::new())
173 /// fn add(&mut self, elem: i32) {
174 /// self.0.push(elem);
178 /// // and we'll implement IntoIterator
179 /// impl IntoIterator for MyCollection {
181 /// type IntoIter = ::std::vec::IntoIter<i32>;
183 /// fn into_iter(self) -> Self::IntoIter {
184 /// self.0.into_iter()
188 /// // Now we can make a new collection...
189 /// let mut c = MyCollection::new();
191 /// // ... add some stuff to it ...
196 /// // ... and then turn it into an Iterator:
197 /// for (i, n) in c.into_iter().enumerate() {
198 /// assert_eq!(i as i32, n);
202 /// It is common to use `IntoIterator` as a trait bound. This allows
203 /// the input collection type to change, so long as it is still an
204 /// iterator. Additional bounds can be specified by restricting on
208 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
209 /// where T: IntoIterator,
210 /// T::Item : std::fmt::Debug,
214 /// .map(|item| format!("{:?}", item))
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub trait IntoIterator {
220 /// The type of the elements being iterated over.
221 #[stable(feature = "rust1", since = "1.0.0")]
224 /// Which kind of iterator are we turning this into?
225 #[stable(feature = "rust1", since = "1.0.0")]
226 type IntoIter: Iterator<Item=Self::Item>;
228 /// Creates an iterator from a value.
230 /// See the [module-level documentation] for more.
232 /// [module-level documentation]: index.html
239 /// let v = vec![1, 2, 3];
240 /// let mut iter = v.into_iter();
242 /// assert_eq!(Some(1), iter.next());
243 /// assert_eq!(Some(2), iter.next());
244 /// assert_eq!(Some(3), iter.next());
245 /// assert_eq!(None, iter.next());
247 #[stable(feature = "rust1", since = "1.0.0")]
248 fn into_iter(self) -> Self::IntoIter;
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<I: Iterator> IntoIterator for I {
256 fn into_iter(self) -> I {
261 /// Extend a collection with the contents of an iterator.
263 /// Iterators produce a series of values, and collections can also be thought
264 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
265 /// to extend a collection by including the contents of that iterator. When
266 /// extending a collection with an already existing key, that entry is updated
267 /// or, in the case of collections that permit multiple entries with equal
268 /// keys, that entry is inserted.
275 /// // You can extend a String with some chars:
276 /// let mut message = String::from("The first three letters are: ");
278 /// message.extend(&['a', 'b', 'c']);
280 /// assert_eq!("abc", &message[29..32]);
283 /// Implementing `Extend`:
286 /// // A sample collection, that's just a wrapper over Vec<T>
288 /// struct MyCollection(Vec<i32>);
290 /// // Let's give it some methods so we can create one and add things
292 /// impl MyCollection {
293 /// fn new() -> MyCollection {
294 /// MyCollection(Vec::new())
297 /// fn add(&mut self, elem: i32) {
298 /// self.0.push(elem);
302 /// // since MyCollection has a list of i32s, we implement Extend for i32
303 /// impl Extend<i32> for MyCollection {
305 /// // This is a bit simpler with the concrete type signature: we can call
306 /// // extend on anything which can be turned into an Iterator which gives
307 /// // us i32s. Because we need i32s to put into MyCollection.
308 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
310 /// // The implementation is very straightforward: loop through the
311 /// // iterator, and add() each element to ourselves.
312 /// for elem in iter {
318 /// let mut c = MyCollection::new();
324 /// // let's extend our collection with three more numbers
325 /// c.extend(vec![1, 2, 3]);
327 /// // we've added these elements onto the end
328 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub trait Extend<A> {
332 /// Extends a collection with the contents of an iterator.
334 /// As this is the only method for this trait, the [trait-level] docs
335 /// contain more details.
337 /// [trait-level]: trait.Extend.html
344 /// // You can extend a String with some chars:
345 /// let mut message = String::from("abc");
347 /// message.extend(['d', 'e', 'f'].iter());
349 /// assert_eq!("abcdef", &message);
351 #[stable(feature = "rust1", since = "1.0.0")]
352 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
355 /// An iterator able to yield elements from both ends.
357 /// Something that implements `DoubleEndedIterator` has one extra capability
358 /// over something that implements [`Iterator`]: the ability to also take
359 /// `Item`s from the back, as well as the front.
361 /// It is important to note that both back and forth work on the same range,
362 /// and do not cross: iteration is over when they meet in the middle.
364 /// In a similar fashion to the [`Iterator`] protocol, once a
365 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
366 /// may or may not ever return `Some` again. `next()` and `next_back()` are
367 /// interchangeable for this purpose.
369 /// [`Iterator`]: trait.Iterator.html
376 /// let numbers = vec![1, 2, 3, 4, 5, 6];
378 /// let mut iter = numbers.iter();
380 /// assert_eq!(Some(&1), iter.next());
381 /// assert_eq!(Some(&6), iter.next_back());
382 /// assert_eq!(Some(&5), iter.next_back());
383 /// assert_eq!(Some(&2), iter.next());
384 /// assert_eq!(Some(&3), iter.next());
385 /// assert_eq!(Some(&4), iter.next());
386 /// assert_eq!(None, iter.next());
387 /// assert_eq!(None, iter.next_back());
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub trait DoubleEndedIterator: Iterator {
391 /// Removes and returns an element from the end of the iterator.
393 /// Returns `None` when there are no more elements.
395 /// The [trait-level] docs contain more details.
397 /// [trait-level]: trait.DoubleEndedIterator.html
404 /// let numbers = vec![1, 2, 3, 4, 5, 6];
406 /// let mut iter = numbers.iter();
408 /// assert_eq!(Some(&1), iter.next());
409 /// assert_eq!(Some(&6), iter.next_back());
410 /// assert_eq!(Some(&5), iter.next_back());
411 /// assert_eq!(Some(&2), iter.next());
412 /// assert_eq!(Some(&3), iter.next());
413 /// assert_eq!(Some(&4), iter.next());
414 /// assert_eq!(None, iter.next());
415 /// assert_eq!(None, iter.next_back());
417 #[stable(feature = "rust1", since = "1.0.0")]
418 fn next_back(&mut self) -> Option<Self::Item>;
420 /// This is the reverse version of [`try_fold()`]: it takes elements
421 /// starting from the back of the iterator.
423 /// [`try_fold()`]: trait.Iterator.html#method.try_fold
430 /// let a = ["1", "2", "3"];
431 /// let sum = a.iter()
432 /// .map(|&s| s.parse::<i32>())
433 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
434 /// assert_eq!(sum, Ok(6));
437 /// Short-circuiting:
440 /// let a = ["1", "rust", "3"];
441 /// let mut it = a.iter();
444 /// .map(|&s| s.parse::<i32>())
445 /// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
446 /// assert!(sum.is_err());
448 /// // Because it short-circuited, the remaining elements are still
449 /// // available through the iterator.
450 /// assert_eq!(it.next_back(), Some(&"1"));
453 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
454 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
455 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
457 let mut accum = init;
458 while let Some(x) = self.next_back() {
459 accum = f(accum, x)?;
464 /// An iterator method that reduces the iterator's elements to a single,
465 /// final value, starting from the back.
467 /// This is the reverse version of [`fold()`]: it takes elements starting from
468 /// the back of the iterator.
470 /// `rfold()` takes two arguments: an initial value, and a closure with two
471 /// arguments: an 'accumulator', and an element. The closure returns the value that
472 /// the accumulator should have for the next iteration.
474 /// The initial value is the value the accumulator will have on the first
477 /// After applying this closure to every element of the iterator, `rfold()`
478 /// returns the accumulator.
480 /// This operation is sometimes called 'reduce' or 'inject'.
482 /// Folding is useful whenever you have a collection of something, and want
483 /// to produce a single value from it.
485 /// [`fold()`]: trait.Iterator.html#method.fold
492 /// let a = [1, 2, 3];
494 /// // the sum of all of the elements of a
495 /// let sum = a.iter()
496 /// .rfold(0, |acc, &x| acc + x);
498 /// assert_eq!(sum, 6);
501 /// This example builds a string, starting with an initial value
502 /// and continuing with each element from the back until the front:
505 /// let numbers = [1, 2, 3, 4, 5];
507 /// let zero = "0".to_string();
509 /// let result = numbers.iter().rfold(zero, |acc, &x| {
510 /// format!("({} + {})", x, acc)
513 /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
516 #[stable(feature = "iter_rfold", since = "1.27.0")]
517 fn rfold<B, F>(mut self, accum: B, mut f: F) -> B where
518 Self: Sized, F: FnMut(B, Self::Item) -> B,
520 self.try_rfold(accum, move |acc, x| AlwaysOk(f(acc, x))).0
523 /// Searches for an element of an iterator from the back that satisfies a predicate.
525 /// `rfind()` takes a closure that returns `true` or `false`. It applies
526 /// this closure to each element of the iterator, starting at the end, and if any
527 /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
528 /// `false`, it returns [`None`].
530 /// `rfind()` is short-circuiting; in other words, it will stop processing
531 /// as soon as the closure returns `true`.
533 /// Because `rfind()` takes a reference, and many iterators iterate over
534 /// references, this leads to a possibly confusing situation where the
535 /// argument is a double reference. You can see this effect in the
536 /// examples below, with `&&x`.
538 /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
539 /// [`None`]: ../../std/option/enum.Option.html#variant.None
546 /// let a = [1, 2, 3];
548 /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
550 /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
553 /// Stopping at the first `true`:
556 /// let a = [1, 2, 3];
558 /// let mut iter = a.iter();
560 /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
562 /// // we can still use `iter`, as there are more elements.
563 /// assert_eq!(iter.next_back(), Some(&1));
566 #[stable(feature = "iter_rfind", since = "1.27.0")]
567 fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
569 P: FnMut(&Self::Item) -> bool
571 self.try_rfold((), move |(), x| {
572 if predicate(&x) { LoopState::Break(x) }
573 else { LoopState::Continue(()) }
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
580 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
583 /// An iterator that knows its exact length.
585 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
586 /// If an iterator knows how many times it can iterate, providing access to
587 /// that information can be useful. For example, if you want to iterate
588 /// backwards, a good start is to know where the end is.
590 /// When implementing an `ExactSizeIterator`, You must also implement
591 /// [`Iterator`]. When doing so, the implementation of [`size_hint`] *must*
592 /// return the exact size of the iterator.
594 /// [`Iterator`]: trait.Iterator.html
595 /// [`size_hint`]: trait.Iterator.html#method.size_hint
597 /// The [`len`] method has a default implementation, so you usually shouldn't
598 /// implement it. However, you may be able to provide a more performant
599 /// implementation than the default, so overriding it in this case makes sense.
601 /// [`len`]: #method.len
608 /// // a finite range knows exactly how many times it will iterate
611 /// assert_eq!(5, five.len());
614 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
615 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
617 /// [moddocs]: index.html
620 /// # struct Counter {
624 /// # fn new() -> Counter {
625 /// # Counter { count: 0 }
628 /// # impl Iterator for Counter {
629 /// # type Item = usize;
630 /// # fn next(&mut self) -> Option<usize> {
631 /// # self.count += 1;
632 /// # if self.count < 6 {
633 /// # Some(self.count)
639 /// impl ExactSizeIterator for Counter {
640 /// // We can easily calculate the remaining number of iterations.
641 /// fn len(&self) -> usize {
646 /// // And now we can use it!
648 /// let counter = Counter::new();
650 /// assert_eq!(5, counter.len());
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub trait ExactSizeIterator: Iterator {
654 /// Returns the exact number of times the iterator will iterate.
656 /// This method has a default implementation, so you usually should not
657 /// implement it directly. However, if you can provide a more efficient
658 /// implementation, you can do so. See the [trait-level] docs for an
661 /// This function has the same safety guarantees as the [`size_hint`]
664 /// [trait-level]: trait.ExactSizeIterator.html
665 /// [`size_hint`]: trait.Iterator.html#method.size_hint
672 /// // a finite range knows exactly how many times it will iterate
675 /// assert_eq!(5, five.len());
678 #[stable(feature = "rust1", since = "1.0.0")]
679 fn len(&self) -> usize {
680 let (lower, upper) = self.size_hint();
681 // Note: This assertion is overly defensive, but it checks the invariant
682 // guaranteed by the trait. If this trait were rust-internal,
683 // we could use debug_assert!; assert_eq! will check all Rust user
684 // implementations too.
685 assert_eq!(upper, Some(lower));
689 /// Returns whether the iterator is empty.
691 /// This method has a default implementation using `self.len()`, so you
692 /// don't need to implement it yourself.
699 /// #![feature(exact_size_is_empty)]
701 /// let mut one_element = std::iter::once(0);
702 /// assert!(!one_element.is_empty());
704 /// assert_eq!(one_element.next(), Some(0));
705 /// assert!(one_element.is_empty());
707 /// assert_eq!(one_element.next(), None);
710 #[unstable(feature = "exact_size_is_empty", issue = "35428")]
711 fn is_empty(&self) -> bool {
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {
718 fn len(&self) -> usize {
721 fn is_empty(&self) -> bool {
726 /// Trait to represent types that can be created by summing up an iterator.
728 /// This trait is used to implement the [`sum`] method on iterators. Types which
729 /// implement the trait can be generated by the [`sum`] method. Like
730 /// [`FromIterator`] this trait should rarely be called directly and instead
731 /// interacted with through [`Iterator::sum`].
733 /// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum
734 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
735 /// [`Iterator::sum`]: ../../std/iter/trait.Iterator.html#method.sum
736 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
737 pub trait Sum<A = Self>: Sized {
738 /// Method which takes an iterator and generates `Self` from the elements by
739 /// "summing up" the items.
740 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
741 fn sum<I: Iterator<Item=A>>(iter: I) -> Self;
744 /// Trait to represent types that can be created by multiplying elements of an
747 /// This trait is used to implement the [`product`] method on iterators. Types
748 /// which implement the trait can be generated by the [`product`] method. Like
749 /// [`FromIterator`] this trait should rarely be called directly and instead
750 /// interacted with through [`Iterator::product`].
752 /// [`product`]: ../../std/iter/trait.Product.html#tymethod.product
753 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
754 /// [`Iterator::product`]: ../../std/iter/trait.Iterator.html#method.product
755 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
756 pub trait Product<A = Self>: Sized {
757 /// Method which takes an iterator and generates `Self` from the elements by
758 /// multiplying the items.
759 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
760 fn product<I: Iterator<Item=A>>(iter: I) -> Self;
763 // NB: explicitly use Add and Mul here to inherit overflow checks
764 macro_rules! integer_sum_product {
765 (@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
768 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
769 iter.fold($zero, Add::add)
774 impl Product for $a {
775 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
776 iter.fold($one, Mul::mul)
781 impl<'a> Sum<&'a $a> for $a {
782 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
783 iter.fold($zero, Add::add)
788 impl<'a> Product<&'a $a> for $a {
789 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
790 iter.fold($one, Mul::mul)
795 integer_sum_product!(@impls 0, 1,
796 #[stable(feature = "iter_arith_traits", since = "1.12.0")],
798 integer_sum_product!(@impls Wrapping(0), Wrapping(1),
799 #[stable(feature = "wrapping_iter_arith", since = "1.14.0")],
804 macro_rules! float_sum_product {
805 ($($a:ident)*) => ($(
806 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
808 fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
809 iter.fold(0.0, |a, b| a + b)
813 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
814 impl Product for $a {
815 fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
816 iter.fold(1.0, |a, b| a * b)
820 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
821 impl<'a> Sum<&'a $a> for $a {
822 fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
823 iter.fold(0.0, |a, b| a + *b)
827 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
828 impl<'a> Product<&'a $a> for $a {
829 fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
830 iter.fold(1.0, |a, b| a * *b)
836 integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
837 float_sum_product! { f32 f64 }
839 /// An iterator adapter that produces output as long as the underlying
840 /// iterator produces `Result::Ok` values.
842 /// If an error is encountered, the iterator stops and the error is
843 /// stored. The error may be recovered later via `reconstruct`.
844 struct ResultShunt<I, E> {
849 impl<I, T, E> ResultShunt<I, E>
850 where I: Iterator<Item = Result<T, E>>
852 /// Process the given iterator as if it yielded a `T` instead of a
853 /// `Result<T, _>`. Any errors will stop the inner iterator and
854 /// the overall result will be an error.
855 pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
856 where F: FnMut(&mut Self) -> U
858 let mut shunt = ResultShunt::new(iter);
859 let value = f(shunt.by_ref());
860 shunt.reconstruct(value)
863 fn new(iter: I) -> Self {
870 /// Consume the adapter and rebuild a `Result` value. This should
871 /// *always* be called, otherwise any potential error would be
873 fn reconstruct<U>(self, val: U) -> Result<U, E> {
881 impl<I, T, E> Iterator for ResultShunt<I, E>
882 where I: Iterator<Item = Result<T, E>>
886 fn next(&mut self) -> Option<Self::Item> {
887 match self.iter.next() {
888 Some(Ok(v)) => Some(v),
890 self.error = Some(e);
897 fn size_hint(&self) -> (usize, Option<usize>) {
898 if self.error.is_some() {
901 let (_, upper) = self.iter.size_hint();
907 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
908 impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
911 /// Takes each element in the `Iterator`: if it is an `Err`, no further
912 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
913 /// the sum of all elements is returned.
917 /// This sums up every integer in a vector, rejecting the sum if a negative
918 /// element is encountered:
921 /// let v = vec![1, 2];
922 /// let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
923 /// if x < 0 { Err("Negative element found") }
926 /// assert_eq!(res, Ok(3));
928 fn sum<I>(iter: I) -> Result<T, E>
929 where I: Iterator<Item = Result<U, E>>,
931 ResultShunt::process(iter, |i| i.sum())
935 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
936 impl<T, U, E> Product<Result<U, E>> for Result<T, E>
939 /// Takes each element in the `Iterator`: if it is an `Err`, no further
940 /// elements are taken, and the `Err` is returned. Should no `Err` occur,
941 /// the product of all elements is returned.
942 fn product<I>(iter: I) -> Result<T, E>
943 where I: Iterator<Item = Result<U, E>>,
945 ResultShunt::process(iter, |i| i.product())
949 /// An iterator that always continues to yield `None` when exhausted.
951 /// Calling next on a fused iterator that has returned `None` once is guaranteed
952 /// to return [`None`] again. This trait should be implemented by all iterators
953 /// that behave this way because it allows for some significant optimizations.
955 /// Note: In general, you should not use `FusedIterator` in generic bounds if
956 /// you need a fused iterator. Instead, you should just call [`Iterator::fuse`]
957 /// on the iterator. If the iterator is already fused, the additional [`Fuse`]
958 /// wrapper will be a no-op with no performance penalty.
960 /// [`None`]: ../../std/option/enum.Option.html#variant.None
961 /// [`Iterator::fuse`]: ../../std/iter/trait.Iterator.html#method.fuse
962 /// [`Fuse`]: ../../std/iter/struct.Fuse.html
963 #[stable(feature = "fused", since = "1.26.0")]
964 pub trait FusedIterator: Iterator {}
966 #[stable(feature = "fused", since = "1.26.0")]
967 impl<'a, I: FusedIterator + ?Sized> FusedIterator for &'a mut I {}
969 /// An iterator that reports an accurate length using size_hint.
971 /// The iterator reports a size hint where it is either exact
972 /// (lower bound is equal to upper bound), or the upper bound is [`None`].
973 /// The upper bound must only be [`None`] if the actual iterator length is
974 /// larger than [`usize::MAX`]. In that case, the lower bound must be
975 /// [`usize::MAX`], resulting in a [`.size_hint`] of `(usize::MAX, None)`.
977 /// The iterator must produce exactly the number of elements it reported
978 /// or diverge before reaching the end.
982 /// This trait must only be implemented when the contract is upheld.
983 /// Consumers of this trait must inspect [`.size_hint`]’s upper bound.
985 /// [`None`]: ../../std/option/enum.Option.html#variant.None
986 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
987 /// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint
988 #[unstable(feature = "trusted_len", issue = "37572")]
989 pub unsafe trait TrustedLen : Iterator {}
991 #[unstable(feature = "trusted_len", issue = "37572")]
992 unsafe impl<'a, I: TrustedLen + ?Sized> TrustedLen for &'a mut I {}