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