pub trait EnsureAddAssign: CheckedAdd + PartialOrd + Zero {
    // Provided method
    fn ensure_add_assign(&mut self, v: Self) -> Result<(), ArithmeticError> { ... }
}
Expand description

Performs self addition that returns ArithmeticError instead of wrapping around on overflow.

Provided Methods§

source

fn ensure_add_assign(&mut self, v: Self) -> Result<(), ArithmeticError>

Adds two numbers overwriting the left hand one, checking for overflow.

If it fails, ArithmeticError is returned.

§Examples
use sp_arithmetic::traits::EnsureAddAssign;

let mut a: i32 = 10;
let b: i32 = 20;

a.ensure_add_assign(b).unwrap();
assert_eq!(a, 30);
use sp_arithmetic::{traits::EnsureAddAssign, ArithmeticError};

fn overflow() -> Result<(), ArithmeticError> {
    let mut max = u32::MAX;
    max.ensure_add_assign(1)?;
    Ok(())
}

fn underflow() -> Result<(), ArithmeticError> {
    let mut max = i32::MIN;
    max.ensure_add_assign(-1)?;
    Ok(())
}

assert_eq!(overflow(), Err(ArithmeticError::Overflow));
assert_eq!(underflow(), Err(ArithmeticError::Underflow));

Object Safety§

This trait is not object safe.

Implementors§