extract amount method for fungible/s Imbalance (#1847)

Introduces an `extract` amount method for `fungible/s` `Imbalance`.
This commit is contained in:
Muharem
2023-10-16 17:16:59 +02:00
committed by GitHub
parent 646ecd0edb
commit c422e3f577
4 changed files with 33 additions and 0 deletions
@@ -113,6 +113,13 @@ impl<B: Balance, OnDrop: HandleImbalanceDrop<B>, OppositeOnDrop: HandleImbalance
sp_std::mem::forget(self);
(Imbalance::new(first), Imbalance::new(second))
}
fn extract(&mut self, amount: B) -> Self {
let new = self.amount.min(amount);
self.amount = self.amount - new;
Imbalance::new(new)
}
fn merge(mut self, other: Self) -> Self {
self.amount = self.amount.saturating_add(other.amount);
sp_std::mem::forget(other);
@@ -109,6 +109,15 @@ impl<
sp_std::mem::forget(self);
(Imbalance::new(asset.clone(), first), Imbalance::new(asset, second))
}
/// Mutate `self` by extracting a new instance with at most `amount` value, reducing `self`
/// accordingly.
pub fn extract(&mut self, amount: B) -> Self {
let new = self.amount.min(amount);
self.amount = self.amount - new;
Imbalance::new(self.asset.clone(), new)
}
pub fn merge(mut self, other: Self) -> Result<Self, (Self, Self)> {
if self.asset == other.asset {
self.amount = self.amount.saturating_add(other.amount);
@@ -72,6 +72,10 @@ pub trait Imbalance<Balance>: Sized + TryDrop + Default {
/// is guaranteed to be at most `amount` and the second will be the remainder.
fn split(self, amount: Balance) -> (Self, Self);
/// Mutate `self` by extracting a new instance with at most `amount` value, reducing `self`
/// accordingly.
fn extract(&mut self, amount: Balance) -> Self;
/// Consume `self` and return two independent instances; the amounts returned will be in
/// approximately the same ratio as `first`:`second`.
///
@@ -190,6 +194,9 @@ impl<Balance: Default> Imbalance<Balance> for () {
fn split(self, _: Balance) -> (Self, Self) {
((), ())
}
fn extract(&mut self, _: Balance) -> Self {
()
}
fn ration(self, _: u32, _: u32) -> (Self, Self)
where
Balance: From<u32> + Saturating + Div<Output = Balance>,