Skip to content

Commit

Permalink
Implement Sum for an iterator of references to amounts
Browse files Browse the repository at this point in the history
We have `iter::Sum` already for `Amount` and `SignedAmount`. Add
an implementation for each to support iterators that yield references.
  • Loading branch information
tcharding committed Nov 28, 2024
1 parent 31f883a commit 0369e64
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
10 changes: 10 additions & 0 deletions units/src/amount/signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,16 @@ impl core::iter::Sum for SignedAmount {
}
}

impl<'a> core::iter::Sum<&'a SignedAmount> for SignedAmount {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a SignedAmount>,
{
let sats: i64 = iter.map(|amt| amt.0).sum();
SignedAmount::from_sat(sats)
}
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for SignedAmount {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Expand Down
4 changes: 2 additions & 2 deletions units/src/amount/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -825,8 +825,8 @@ fn serde_as_sat_opt() {

#[test]
fn sum_amounts() {
assert_eq!(Amount::from_sat(0), [].into_iter().sum::<Amount>());
assert_eq!(SignedAmount::from_sat(0), [].into_iter().sum::<SignedAmount>());
assert_eq!(Amount::from_sat(0), [].iter().sum::<Amount>());
assert_eq!(SignedAmount::from_sat(0), [].iter().sum::<SignedAmount>());

let amounts = [Amount::from_sat(42), Amount::from_sat(1337), Amount::from_sat(21)];
let sum = amounts.into_iter().sum::<Amount>();
Expand Down
10 changes: 10 additions & 0 deletions units/src/amount/unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,16 @@ impl core::iter::Sum for Amount {
}
}

impl<'a> core::iter::Sum<&'a Amount> for Amount {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Amount>,
{
let sats: u64 = iter.map(|amt| amt.0).sum();
Amount::from_sat(sats)
}
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Amount {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Expand Down

0 comments on commit 0369e64

Please sign in to comment.