Skip to content

Commit 2514d02

Browse files
committed
Use try_fold and try_rfold in default implementations of fold and rfold
1 parent 1db9c06 commit 2514d02

File tree

2 files changed

+6
-14
lines changed

2 files changed

+6
-14
lines changed

Diff for: library/core/src/iter/traits/double_ended.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::marker::Destruct;
2-
use crate::ops::{ControlFlow, Try};
2+
use crate::ops::{ControlFlow, NeverShortCircuit, Try};
33

44
/// An iterator able to yield elements from both ends.
55
///
@@ -297,16 +297,12 @@ pub trait DoubleEndedIterator: Iterator {
297297
#[inline]
298298
#[stable(feature = "iter_rfold", since = "1.27.0")]
299299
#[rustc_do_not_const_check]
300-
fn rfold<B, F>(mut self, init: B, mut f: F) -> B
300+
fn rfold<B, F>(mut self, init: B, f: F) -> B
301301
where
302302
Self: Sized,
303303
F: FnMut(B, Self::Item) -> B,
304304
{
305-
let mut accum = init;
306-
while let Some(x) = self.next_back() {
307-
accum = f(accum, x);
308-
}
309-
accum
305+
self.try_rfold(init, NeverShortCircuit::wrap_mut_2(f)).0
310306
}
311307

312308
/// Searches for an element of an iterator from the back that satisfies a predicate.

Diff for: library/core/src/iter/traits/iterator.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::array;
22
use crate::cmp::{self, Ordering};
33
use crate::marker::Destruct;
4-
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
4+
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, NeverShortCircuit, Residual, Try};
55

66
use super::super::try_process;
77
use super::super::ByRefSized;
@@ -2472,16 +2472,12 @@ pub trait Iterator {
24722472
#[inline]
24732473
#[stable(feature = "rust1", since = "1.0.0")]
24742474
#[rustc_do_not_const_check]
2475-
fn fold<B, F>(mut self, init: B, mut f: F) -> B
2475+
fn fold<B, F>(mut self, init: B, f: F) -> B
24762476
where
24772477
Self: Sized,
24782478
F: FnMut(B, Self::Item) -> B,
24792479
{
2480-
let mut accum = init;
2481-
while let Some(x) = self.next() {
2482-
accum = f(accum, x);
2483-
}
2484-
accum
2480+
self.try_fold(init, NeverShortCircuit::wrap_mut_2(f)).0
24852481
}
24862482

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

0 commit comments

Comments
 (0)