Merge rust-bitcoin/rust-bitcoin#4348: refactor: Replace fold with try_fold

812c21e2e4 refactor: Replace fold with try_fold (yancy)

Pull request description:

  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.

ACKs for top commit:
  apoelstra:
    ACK 812c21e2e4a868046b44728c1a6209a866452820; successfully ran local tests
  tcharding:
    ACK 812c21e2e4

Tree-SHA512: 1cfcd4fa28e2b59daf3744bb5f654f65eb9853c5a36f747cb0859783e7e46c1d02ccb296612b75f7cca10782979ce052cd670c0f23c1030e0a347000d1f6df83
This commit is contained in:
merge-script 2025-04-16 13:56:34 +00:00
commit 551b52c7d1
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 2 additions and 6 deletions

View File

@ -605,9 +605,7 @@ where
T: Iterator<Item = Amount>, T: Iterator<Item = Amount>,
{ {
fn checked_sum(mut self) -> Option<Amount> { fn checked_sum(mut self) -> Option<Amount> {
let first = Some(self.next().unwrap_or_default()); self.try_fold(Amount::ZERO, Amount::checked_add)
self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item)))
} }
} }
@ -616,9 +614,7 @@ where
T: Iterator<Item = SignedAmount>, T: Iterator<Item = SignedAmount>,
{ {
fn checked_sum(mut self) -> Option<SignedAmount> { fn checked_sum(mut self) -> Option<SignedAmount> {
let first = Some(self.next().unwrap_or_default()); self.try_fold(SignedAmount::ZERO, SignedAmount::checked_add)
self.fold(first, |acc, item| acc.and_then(|acc| acc.checked_add(item)))
} }
} }