(self, init: Acc, f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.iter.rfold(init, f)
+ }
+
+ #[inline]
+ fn find(&mut self, predicate: P) -> Option
+ where P: FnMut(&Self::Item) -> bool
+ {
+ self.iter.rfind(predicate)
+ }
+
+ #[inline]
+ fn rposition(&mut self, predicate: P) -> Option where
+ P: FnMut(Self::Item) -> bool
+ {
+ self.iter.position(predicate)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl DoubleEndedIterator for Rev where I: DoubleEndedIterator {
+ #[inline]
+ fn next_back(&mut self) -> Option<::Item> { self.iter.next() }
+
+ #[inline]
+ fn nth_back(&mut self, n: usize) -> Option<::Item> { self.iter.nth(n) }
+
+ fn try_rfold(&mut self, init: B, f: F) -> R where
+ Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try
+ {
+ self.iter.try_fold(init, f)
+ }
+
+ fn rfold(self, init: Acc, f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.iter.fold(init, f)
+ }
+
+ fn rfind(&mut self, predicate: P) -> Option
+ where P: FnMut(&Self::Item) -> bool
+ {
+ self.iter.find(predicate)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl ExactSizeIterator for Rev
+ where I: ExactSizeIterator + DoubleEndedIterator
+{
+ fn len(&self) -> usize {
+ self.iter.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.iter.is_empty()
+ }
+}
+
+#[stable(feature = "fused", since = "1.26.0")]
+impl FusedIterator for Rev
+ where I: FusedIterator + DoubleEndedIterator {}
+
+#[unstable(feature = "trusted_len", issue = "37572")]
+unsafe impl TrustedLen for Rev
+ where I: TrustedLen + DoubleEndedIterator {}
+
+/// An iterator that copies the elements of an underlying iterator.
+///
+/// This `struct` is created by the [`copied`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`copied`]: trait.Iterator.html#method.copied
+/// [`Iterator`]: trait.Iterator.html
+#[unstable(feature = "iter_copied", issue = "57127")]
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[derive(Clone, Debug)]
+pub struct Copied {
+ it: I,
+}
+impl Copied {
+ pub(super) fn new(it: I) -> Copied {
+ Copied { it }
+ }
+}
+
+#[unstable(feature = "iter_copied", issue = "57127")]
+impl<'a, I, T: 'a> Iterator for Copied
+ where I: Iterator- , T: Copy
+{
+ type Item = T;
+
+ fn next(&mut self) -> Option {
+ self.it.next().copied()
+ }
+
+ fn size_hint(&self) -> (usize, Option) {
+ self.it.size_hint()
+ }
+
+ fn try_fold(&mut self, init: B, mut f: F) -> R where
+ Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try
+ {
+ self.it.try_fold(init, move |acc, &elt| f(acc, elt))
+ }
+
+ fn fold(self, init: Acc, mut f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.it.fold(init, move |acc, &elt| f(acc, elt))
+ }
+}
+
+#[unstable(feature = "iter_copied", issue = "57127")]
+impl<'a, I, T: 'a> DoubleEndedIterator for Copied
+ where I: DoubleEndedIterator
- , T: Copy
+{
+ fn next_back(&mut self) -> Option {
+ self.it.next_back().copied()
+ }
+
+ fn try_rfold(&mut self, init: B, mut f: F) -> R where
+ Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try
+ {
+ self.it.try_rfold(init, move |acc, &elt| f(acc, elt))
+ }
+
+ fn rfold(self, init: Acc, mut f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.it.rfold(init, move |acc, &elt| f(acc, elt))
+ }
+}
+
+#[unstable(feature = "iter_copied", issue = "57127")]
+impl<'a, I, T: 'a> ExactSizeIterator for Copied
+ where I: ExactSizeIterator
- , T: Copy
+{
+ fn len(&self) -> usize {
+ self.it.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.it.is_empty()
+ }
+}
+
+#[unstable(feature = "iter_copied", issue = "57127")]
+impl<'a, I, T: 'a> FusedIterator for Copied
+ where I: FusedIterator
- , T: Copy
+{}
+
+#[doc(hidden)]
+unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Copied
+ where I: TrustedRandomAccess
- , T: Copy
+{
+ unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
+ *self.it.get_unchecked(i)
+ }
+
+ #[inline]
+ fn may_have_side_effect() -> bool {
+ I::may_have_side_effect()
+ }
+}
+
+#[unstable(feature = "iter_copied", issue = "57127")]
+unsafe impl<'a, I, T: 'a> TrustedLen for Copied
+ where I: TrustedLen
- ,
+ T: Copy
+{}
+
+/// An iterator that clones the elements of an underlying iterator.
+///
+/// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`cloned`]: trait.Iterator.html#method.cloned
+/// [`Iterator`]: trait.Iterator.html
+#[stable(feature = "iter_cloned", since = "1.1.0")]
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[derive(Clone, Debug)]
+pub struct Cloned {
+ it: I,
+}
+impl Cloned {
+ pub(super) fn new(it: I) -> Cloned {
+ Cloned { it }
+ }
+}
+
+#[stable(feature = "iter_cloned", since = "1.1.0")]
+impl<'a, I, T: 'a> Iterator for Cloned
+ where I: Iterator
- , T: Clone
+{
+ type Item = T;
+
+ fn next(&mut self) -> Option {
+ self.it.next().cloned()
+ }
+
+ fn size_hint(&self) -> (usize, Option) {
+ self.it.size_hint()
+ }
+
+ fn try_fold(&mut self, init: B, mut f: F) -> R where
+ Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try
+ {
+ self.it.try_fold(init, move |acc, elt| f(acc, elt.clone()))
+ }
+
+ fn fold(self, init: Acc, mut f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
+ }
+}
+
+#[stable(feature = "iter_cloned", since = "1.1.0")]
+impl<'a, I, T: 'a> DoubleEndedIterator for Cloned
+ where I: DoubleEndedIterator
- , T: Clone
+{
+ fn next_back(&mut self) -> Option {
+ self.it.next_back().cloned()
+ }
+
+ fn try_rfold(&mut self, init: B, mut f: F) -> R where
+ Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try
+ {
+ self.it.try_rfold(init, move |acc, elt| f(acc, elt.clone()))
+ }
+
+ fn rfold(self, init: Acc, mut f: F) -> Acc
+ where F: FnMut(Acc, Self::Item) -> Acc,
+ {
+ self.it.rfold(init, move |acc, elt| f(acc, elt.clone()))
+ }
+}
+
+#[stable(feature = "iter_cloned", since = "1.1.0")]
+impl<'a, I, T: 'a> ExactSizeIterator for Cloned
+ where I: ExactSizeIterator
- , T: Clone
+{
+ fn len(&self) -> usize {
+ self.it.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.it.is_empty()
+ }
+}
+
+#[stable(feature = "fused", since = "1.26.0")]
+impl<'a, I, T: 'a> FusedIterator for Cloned
+ where I: FusedIterator
- , T: Clone
+{}
+
+#[doc(hidden)]
+unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned
+ where I: TrustedRandomAccess
- , T: Clone
+{
+ default unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
+ self.it.get_unchecked(i).clone()
+ }
+
+ #[inline]
+ default fn may_have_side_effect() -> bool { true }
+}
+
+#[doc(hidden)]
+unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned
+ where I: TrustedRandomAccess
- , T: Copy
+{
+ unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
+ *self.it.get_unchecked(i)
+ }
+
+ #[inline]
+ fn may_have_side_effect() -> bool {
+ I::may_have_side_effect()
+ }
+}
+
+#[unstable(feature = "trusted_len", issue = "37572")]
+unsafe impl<'a, I, T: 'a> TrustedLen for Cloned
+ where I: TrustedLen
- ,
+ T: Clone
+{}
+
+/// An iterator that repeats endlessly.
+///
+/// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`cycle`]: trait.Iterator.html#method.cycle
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Cycle {
+ orig: I,
+ iter: I,
+}
+impl Cycle {
+ pub(super) fn new(iter: I) -> Cycle {
+ Cycle { orig: iter.clone(), iter }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Iterator for Cycle where I: Clone + Iterator {
+ type Item = ::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<::Item> {
+ match self.iter.next() {
+ None => { self.iter = self.orig.clone(); self.iter.next() }
+ y => y
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option) {
+ // the cycle iterator is either empty or infinite
+ match self.orig.size_hint() {
+ sz @ (0, Some(0)) => sz,
+ (0, _) => (0, None),
+ _ => (usize::MAX, None)
+ }
+ }
+}
+
+#[stable(feature = "fused", since = "1.26.0")]
+impl FusedIterator for Cycle where I: Clone + Iterator {}
+
+/// An iterator for stepping iterators by a custom amount.
+///
+/// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
+/// its documentation for more.
+///
+/// [`step_by`]: trait.Iterator.html#method.step_by
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[stable(feature = "iterator_step_by", since = "1.28.0")]
+#[derive(Clone, Debug)]
+pub struct StepBy {
+ iter: I,
+ step: usize,
+ first_take: bool,
+}
+impl StepBy {
+ pub(super) fn new(iter: I, step: usize) -> StepBy {
+ assert!(step != 0);
+ StepBy { iter, step: step - 1, first_take: true }
+ }
+}
+
+#[stable(feature = "iterator_step_by", since = "1.28.0")]
+impl Iterator for StepBy where I: Iterator {
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option {
+ if self.first_take {
+ self.first_take = false;
+ self.iter.next()
+ } else {
+ self.iter.nth(self.step)
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option) {
+ let inner_hint = self.iter.size_hint();
+
+ if self.first_take {
+ let f = |n| if n == 0 { 0 } else { 1 + (n-1)/(self.step+1) };
+ (f(inner_hint.0), inner_hint.1.map(f))
+ } else {
+ let f = |n| n / (self.step+1);
+ (f(inner_hint.0), inner_hint.1.map(f))
+ }
+ }
+
+ #[inline]
+ fn nth(&mut self, mut n: usize) -> Option {
+ if self.first_take {
+ self.first_take = false;
+ let first = self.iter.next();
+ if n == 0 {
+ return first;
+ }
+ n -= 1;
+ }
+ // n and self.step are indices, we need to add 1 to get the amount of elements
+ // When calling `.nth`, we need to subtract 1 again to convert back to an index
+ // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
+ let mut step = self.step + 1;
+ // n + 1 could overflow
+ // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
+ if n == usize::MAX {
+ self.iter.nth(step - 1);
+ } else {
+ n += 1;
+ }
+
+ // overflow handling
+ loop {
+ let mul = n.checked_mul(step);
+ if unsafe { intrinsics::likely(mul.is_some()) } {
+ return self.iter.nth(mul.unwrap() - 1);
+ }
+ let div_n = usize::MAX / n;
+ let div_step = usize::MAX / step;
+ let nth_n = div_n * n;
+ let nth_step = div_step * step;
+ let nth = if nth_n > nth_step {
+ step -= div_n;
+ nth_n
+ } else {
+ n -= div_step;
+ nth_step
+ };
+ self.iter.nth(nth - 1);
+ }
+ }
+}
+
+// StepBy can only make the iterator shorter, so the len will still fit.
+#[stable(feature = "iterator_step_by", since = "1.28.0")]
+impl ExactSizeIterator for StepBy where I: ExactSizeIterator {}
+
+/// An iterator that maps the values of `iter` with `f`.
+///
+/// This `struct` is created by the [`map`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`map`]: trait.Iterator.html#method.map
+/// [`Iterator`]: trait.Iterator.html
+///
+/// # Notes about side effects
+///
+/// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
+/// you can also [`map`] backwards:
+///
+/// ```rust
+/// let v: Vec = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
+///
+/// assert_eq!(v, [4, 3, 2]);
+/// ```
+///
+/// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
+///
+/// But if your closure has state, iterating backwards may act in a way you do
+/// not expect. Let's go through an example. First, in the forward direction:
+///
+/// ```rust
+/// let mut c = 0;
+///
+/// for pair in vec!['a', 'b', 'c'].into_iter()
+/// .map(|letter| { c += 1; (letter, c) }) {
+/// println!("{:?}", pair);
+/// }
+/// ```
+///
+/// This will print "('a', 1), ('b', 2), ('c', 3)".
+///
+/// Now consider this twist where we add a call to `rev`. This version will
+/// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
+/// but the values of the counter still go in order. This is because `map()` is
+/// still being called lazily on each item, but we are popping items off the
+/// back of the vector now, instead of shifting them from the front.
+///
+/// ```rust
+/// let mut c = 0;
+///
+/// for pair in vec!['a', 'b', 'c'].into_iter()
+/// .map(|letter| { c += 1; (letter, c) })
+/// .rev() {
+/// println!("{:?}", pair);
+/// }
+/// ```
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Map {
+ iter: I,
+ f: F,
+}
+impl Map {
+ pub(super) fn new(iter: I, f: F) -> Map {
+ Map { iter, f }
+ }
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl fmt::Debug for Map {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Map")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Iterator for Map where F: FnMut(I::Item) -> B {
+ type Item = B;
+
+ #[inline]
+ fn next(&mut self) -> Option {
+ self.iter.next().map(&mut self.f)
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option) {
+ self.iter.size_hint()
+ }
+
+ fn try_fold(&mut self, init: Acc, mut g: G) -> R where
+ Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try
+ {
+ let f = &mut self.f;
+ self.iter.try_fold(init, move |acc, elt| g(acc, f(elt)))
+ }
+
+ fn fold(self, init: Acc, mut g: G) -> Acc
+ where G: FnMut(Acc, Self::Item) -> Acc,
+ {
+ let mut f = self.f;
+ self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl DoubleEndedIterator for Map where
+ F: FnMut(I::Item) -> B,
+{
+ #[inline]
+ fn next_back(&mut self) -> Option {
+ self.iter.next_back().map(&mut self.f)
+ }
+
+ fn try_rfold(&mut self, init: Acc, mut g: G) -> R where
+ Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try
+ {
+ let f = &mut self.f;
+ self.iter.try_rfold(init, move |acc, elt| g(acc, f(elt)))
+ }
+
+ fn rfold(self, init: Acc, mut g: G) -> Acc
+ where G: FnMut(Acc, Self::Item) -> Acc,
+ {
+ let mut f = self.f;
+ self.iter.rfold(init, move |acc, elt| g(acc, f(elt)))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl ExactSizeIterator for Map
+ where F: FnMut(I::Item) -> B
+{
+ fn len(&self) -> usize {
+ self.iter.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.iter.is_empty()
+ }
+}
+
+#[stable(feature = "fused", since = "1.26.0")]
+impl FusedIterator for Map
+ where F: FnMut(I::Item) -> B {}
+
+#[unstable(feature = "trusted_len", issue = "37572")]
+unsafe impl TrustedLen for Map
+ where I: TrustedLen,
+ F: FnMut(I::Item) -> B {}
+
+#[doc(hidden)]
+unsafe impl TrustedRandomAccess for Map
+ where I: TrustedRandomAccess,
+ F: FnMut(I::Item) -> B,
+{
+ unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
+ (self.f)(self.iter.get_unchecked(i))
+ }
+ #[inline]
+ fn may_have_side_effect() -> bool { true }
+}
+
+/// An iterator that filters the elements of `iter` with `predicate`.
+///
+/// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`filter`]: trait.Iterator.html#method.filter
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Filter {
+ iter: I,
+ predicate: P,
+}
+impl Filter {
+ pub(super) fn new(iter: I, predicate: P) -> Filter {
+ Filter { iter, predicate }
+ }
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl fmt::Debug for Filter {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Filter")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Iterator for Filter where P: FnMut(&I::Item) -> bool {
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option {
+ for x in &mut self.iter {
+ if (self.predicate)(&x) {
+ return Some(x);
+ }
+ }
+ None
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the predicate
+ }
+
+ // this special case allows the compiler to make `.filter(_).count()`
+ // branchless. Barring perfect branch prediction (which is unattainable in
+ // the general case), this will be much faster in >90% of cases (containing
+ // virtually all real workloads) and only a tiny bit slower in the rest.
+ //
+ // Having this specialization thus allows us to write `.filter(p).count()`
+ // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
+ // less readable and also less backwards-compatible to Rust before 1.10.
+ //
+ // Using the branchless version will also simplify the LLVM byte code, thus
+ // leaving more budget for LLVM optimizations.
+ #[inline]
+ fn count(mut self) -> usize {
+ let mut count = 0;
+ for x in &mut self.iter {
+ count += (self.predicate)(&x) as usize;
+ }
+ count
+ }
+
+ #[inline]
+ fn try_fold(&mut self, init: Acc, mut fold: Fold) -> R where
+ Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try
+ {
+ let predicate = &mut self.predicate;
+ self.iter.try_fold(init, move |acc, item| if predicate(&item) {
+ fold(acc, item)
+ } else {
+ Try::from_ok(acc)
+ })
+ }
+
+ #[inline]
+ fn fold(self, init: Acc, mut fold: Fold) -> Acc
+ where Fold: FnMut(Acc, Self::Item) -> Acc,
+ {
+ let mut predicate = self.predicate;
+ self.iter.fold(init, move |acc, item| if predicate(&item) {
+ fold(acc, item)
+ } else {
+ acc
+ })
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl DoubleEndedIterator for Filter
+ where P: FnMut(&I::Item) -> bool,
+{
+ #[inline]
+ fn next_back(&mut self) -> Option {
+ for x in self.iter.by_ref().rev() {
+ if (self.predicate)(&x) {
+ return Some(x);
+ }
+ }
+ None
+ }
+
+ #[inline]
+ fn try_rfold(&mut self, init: Acc, mut fold: Fold) -> R where
+ Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try
+ {
+ let predicate = &mut self.predicate;
+ self.iter.try_rfold(init, move |acc, item| if predicate(&item) {
+ fold(acc, item)
+ } else {
+ Try::from_ok(acc)
+ })
+ }
+
+ #[inline]
+ fn rfold(self, init: Acc, mut fold: Fold) -> Acc
+ where Fold: FnMut(Acc, Self::Item) -> Acc,
+ {
+ let mut predicate = self.predicate;
+ self.iter.rfold(init, move |acc, item| if predicate(&item) {
+ fold(acc, item)
+ } else {
+ acc
+ })
+ }
+}
+
+#[stable(feature = "fused", since = "1.26.0")]
+impl FusedIterator for Filter
+ where P: FnMut(&I::Item) -> bool {}
+
+/// An iterator that uses `f` to both filter and map elements from `iter`.
+///
+/// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`filter_map`]: trait.Iterator.html#method.filter_map
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterators are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct FilterMap {
+ iter: I,
+ f: F,
+}
+impl FilterMap