Skip to content

Use try_fold and try_rfold in default implementations of fold and rfold #106463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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