From 812c21e2e4a868046b44728c1a6209a866452820 Mon Sep 17 00:00:00 2001 From: yancy Date: Tue, 15 Apr 2025 07:41:52 -0500 Subject: [PATCH] refactor: Replace fold with try_fold The and_then combinator performs a kind of bitwise and operation on two Option types here. This is useful since the `checked` arithmetic returns an option thereby accumulating Option types. Therefore, either the checked arithmetic operation performs the addition of the unwrapped accumulator, or it returns None. Instead of using `and_then` use the provided `try_fold` method which will short circuit on `None` when the checked arithmetic is used. Also, simplify the staring condition using `Amount:ZERO` since this is logically equivalent to using the first value if one exists. Lastly, by using the built in `try_fold`, it's possible the performance will be improved by making use of the short circuit ability instead of evaluating each item even when the accumulator holds a None type. --- units/src/amount/mod.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/units/src/amount/mod.rs b/units/src/amount/mod.rs index 6fb09fbcf..9a4f715ba 100644 --- a/units/src/amount/mod.rs +++ b/units/src/amount/mod.rs @@ -605,9 +605,7 @@ where T: Iterator, { fn checked_sum(mut self) -> Option { - let first = Some(self.next().unwrap_or_default()); - - self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item))) + self.try_fold(Amount::ZERO, Amount::checked_add) } } @@ -616,9 +614,7 @@ where T: Iterator, { fn checked_sum(mut self) -> Option { - let first = Some(self.next().unwrap_or_default()); - - self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item))) + self.try_fold(SignedAmount::ZERO, SignedAmount::checked_add) } }