Trait sp_arithmetic::traits::EnsureSubAssign
source · pub trait EnsureSubAssign: CheckedSub + PartialOrd + Zero {
// Provided method
fn ensure_sub_assign(&mut self, v: Self) -> Result<(), ArithmeticError> { ... }
}
Expand description
Performs self subtraction that returns ArithmeticError
instead of wrapping around on
underflow.
Provided Methods§
sourcefn ensure_sub_assign(&mut self, v: Self) -> Result<(), ArithmeticError>
fn ensure_sub_assign(&mut self, v: Self) -> Result<(), ArithmeticError>
Subtracts two numbers overwriting the left hand one, checking for overflow.
If it fails, ArithmeticError
is returned.
Examples
use sp_arithmetic::traits::EnsureSubAssign;
let mut a: i32 = 10;
let b: i32 = 20;
a.ensure_sub_assign(b).unwrap();
assert_eq!(a, -10);
use sp_arithmetic::{traits::EnsureSubAssign, ArithmeticError};
fn underflow() -> Result<(), ArithmeticError> {
let mut zero: u32 = 0;
zero.ensure_sub_assign(1)?;
Ok(())
}
fn overflow() -> Result<(), ArithmeticError> {
let mut zero = i32::MAX;
zero.ensure_sub_assign(-1)?;
Ok(())
}
assert_eq!(underflow(), Err(ArithmeticError::Underflow));
assert_eq!(overflow(), Err(ArithmeticError::Overflow));