frame_support/traits/tokens/imbalance/
signed_imbalance.rs1use super::super::imbalance::Imbalance;
21use crate::traits::misc::SameOrOther;
22use codec::FullCodec;
23use core::fmt::Debug;
24use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize};
25
26pub enum SignedImbalance<B, PositiveImbalance: Imbalance<B>> {
28 Positive(PositiveImbalance),
30 Negative(PositiveImbalance::Opposite),
32}
33
34impl<
35 P: Imbalance<B, Opposite = N>,
36 N: Imbalance<B, Opposite = P>,
37 B: AtLeast32BitUnsigned + FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default,
38 > SignedImbalance<B, P>
39{
40 pub fn zero() -> Self {
42 SignedImbalance::Positive(P::zero())
43 }
44
45 pub fn drop_zero(self) -> Result<(), Self> {
47 match self {
48 SignedImbalance::Positive(x) => x.drop_zero().map_err(SignedImbalance::Positive),
49 SignedImbalance::Negative(x) => x.drop_zero().map_err(SignedImbalance::Negative),
50 }
51 }
52
53 pub fn merge(self, other: Self) -> Self {
56 match (self, other) {
57 (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) =>
58 SignedImbalance::Positive(one.merge(other)),
59 (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) =>
60 SignedImbalance::Negative(one.merge(other)),
61 (SignedImbalance::Positive(one), SignedImbalance::Negative(other)) => {
62 match one.offset(other) {
63 SameOrOther::Same(positive) => SignedImbalance::Positive(positive),
64 SameOrOther::Other(negative) => SignedImbalance::Negative(negative),
65 SameOrOther::None => SignedImbalance::Positive(P::zero()),
66 }
67 },
68 (one, other) => other.merge(one),
69 }
70 }
71}