Skip to content

Commit

Permalink
Use try_fold and try_rfold in default implementations of fold and rfold
Browse files Browse the repository at this point in the history
  • Loading branch information
clarfonthey committed Mar 22, 2023
1 parent 1db9c06 commit 2514d02
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 14 deletions.
10 changes: 3 additions & 7 deletions library/core/src/iter/traits/double_ended.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::marker::Destruct;
use crate::ops::{ControlFlow, Try};
use crate::ops::{ControlFlow, NeverShortCircuit, Try};

/// An iterator able to yield elements from both ends.
///
Expand Down Expand Up @@ -297,16 +297,12 @@ pub trait DoubleEndedIterator: Iterator {
#[inline]
#[stable(feature = "iter_rfold", since = "1.27.0")]
#[rustc_do_not_const_check]
fn rfold<B, F>(mut self, init: B, mut f: F) -> B
fn rfold<B, F>(mut self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;
while let Some(x) = self.next_back() {
accum = f(accum, x);
}
accum
self.try_rfold(init, NeverShortCircuit::wrap_mut_2(f)).0
}

/// Searches for an element of an iterator from the back that satisfies a predicate.
Expand Down
10 changes: 3 additions & 7 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::array;
use crate::cmp::{self, Ordering};
use crate::marker::Destruct;
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, NeverShortCircuit, Residual, Try};

use super::super::try_process;
use super::super::ByRefSized;
Expand Down Expand Up @@ -2472,16 +2472,12 @@ pub trait Iterator {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_do_not_const_check]
fn fold<B, F>(mut self, init: B, mut f: F) -> B
fn fold<B, F>(mut self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;
while let Some(x) = self.next() {
accum = f(accum, x);
}
accum
self.try_fold(init, NeverShortCircuit::wrap_mut_2(f)).0
}

/// Reduces the elements to a single one, by repeatedly applying a reducing
Expand Down

0 comments on commit 2514d02

Please sign in to comment.