Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checked add and sub for ValueSum #70

Merged
merged 2 commits into from
Jan 30, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 39 additions & 22 deletions masp_primitives/src/transaction/components/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,17 +426,7 @@ where
type Output = ValueSum<Unit, Value>;

fn add(self, rhs: &ValueSum<Unit, Value>) -> Self::Output {
let mut comps = self.0.clone();
for (atype, amount) in rhs.components() {
comps.insert(
atype.clone(),
self.get(atype)
.checked_add(amount)
.expect("overflow detected"),
);
}
comps.retain(|_, v| *v != Value::default());
ValueSum(comps)
self.checked_add(rhs).expect("overflow detected")
}
}

Expand All @@ -459,6 +449,28 @@ where
}
}

impl<Unit, Value> CheckedAdd for ValueSum<Unit, Value>
where
Unit: Hash + Ord + BorshSerialize + BorshDeserialize + Clone,
Value: BorshSerialize
+ BorshDeserialize
+ PartialEq
+ Eq
+ Copy
+ Default
+ PartialOrd
+ CheckedAdd,
{
fn checked_add(&self, v: &Self) -> Option<Self> {
let mut comps = self.0.clone();
for (atype, amount) in v.components() {
comps.insert(atype.clone(), self.get(atype).checked_add(amount)?);
}
comps.retain(|_, v| *v != Value::default());
Some(ValueSum(comps))
}
}

impl<Unit, Value> SubAssign<&ValueSum<Unit, Value>> for ValueSum<Unit, Value>
where
Unit: Hash + Ord + BorshSerialize + BorshDeserialize + Clone,
Expand Down Expand Up @@ -528,17 +540,7 @@ where
type Output = ValueSum<Unit, Value>;

fn sub(self, rhs: &ValueSum<Unit, Value>) -> Self::Output {
let mut comps = self.0.clone();
for (atype, amount) in rhs.components() {
comps.insert(
atype.clone(),
self.get(atype)
.checked_sub(amount)
.expect("overflow detected"),
);
}
comps.retain(|_, v| *v != Value::default());
ValueSum(comps)
self.checked_sub(rhs).expect("underflow detected")
}
}

Expand All @@ -554,6 +556,21 @@ where
}
}

impl<Unit, Value> CheckedSub for ValueSum<Unit, Value>
where
Unit: Hash + Ord + BorshSerialize + BorshDeserialize + Clone,
Value: BorshSerialize + BorshDeserialize + PartialEq + Eq + Copy + Default + CheckedSub,
{
fn checked_sub(&self, v: &Self) -> Option<Self> {
let mut comps = self.0.clone();
for (atype, amount) in v.components() {
comps.insert(atype.clone(), self.get(atype).checked_sub(amount)?);
}
comps.retain(|_, v| *v != Value::default());
Some(ValueSum(comps))
}
}

impl<Unit, Value> Sum for ValueSum<Unit, Value>
where
Unit: Hash + Ord + BorshSerialize + BorshDeserialize + Clone,
Expand Down
Loading