From 2514d02c55b87712a26eff25dbce9fb08e353888 Mon Sep 17 00:00:00 2001 From: ltdk Date: Wed, 4 Jan 2023 15:44:51 -0500 Subject: [PATCH] Use try_fold and try_rfold in default implementations of fold and rfold --- library/core/src/iter/traits/double_ended.rs | 10 +++------- library/core/src/iter/traits/iterator.rs | 10 +++------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index 7a10dea500a96..a244cc1884853 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -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. /// @@ -297,16 +297,12 @@ pub trait DoubleEndedIterator: Iterator { #[inline] #[stable(feature = "iter_rfold", since = "1.27.0")] #[rustc_do_not_const_check] - fn rfold(mut self, init: B, mut f: F) -> B + fn rfold(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. diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 16c9f668b8ea8..537d7b7470fd6 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -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; @@ -2472,16 +2472,12 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_do_not_const_check] - fn fold(mut self, init: B, mut f: F) -> B + fn fold(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