Trait sp_arithmetic::traits::EnsureSub
source · pub trait EnsureSub: EnsureSubAssign {
// Provided method
fn ensure_sub(self, v: Self) -> Result<Self, ArithmeticError> { ... }
}
Expand description
Performs subtraction that returns ArithmeticError
instead of wrapping around on
underflow.
Provided Methods§
sourcefn ensure_sub(self, v: Self) -> Result<Self, ArithmeticError>
fn ensure_sub(self, v: Self) -> Result<Self, ArithmeticError>
Subtracts two numbers, checking for overflow.
If it fails, ArithmeticError
is returned.
Similar to CheckedSub::checked_sub()
but returning an ArithmeticError
error.
Examples
use sp_arithmetic::traits::EnsureSub;
let a: i32 = 10;
let b: i32 = 20;
assert_eq!(a.ensure_sub(b), Ok(-10));
use sp_arithmetic::{traits::EnsureSub, ArithmeticError};
fn underflow() -> Result<(), ArithmeticError> {
0u32.ensure_sub(1)?;
Ok(())
}
fn overflow() -> Result<(), ArithmeticError> {
i32::MAX.ensure_sub(-1)?;
Ok(())
}
assert_eq!(underflow(), Err(ArithmeticError::Underflow));
assert_eq!(overflow(), Err(ArithmeticError::Overflow));