SafeAdd

Trait SafeAdd 

Source
pub trait SafeAdd: Copy + Add<Output = Self> {
    // Required method
    fn safe_add(self, rhs: Self) -> Result<Self, SafeMathError>;
}
Expand description

Safe addition operation with overflow checking.

This trait provides checked addition that returns a Result instead of panicking or wrapping on overflow.

§Arguments

  • rhs - Right-hand side operand.

§Returns

  • Ok(result) - The sum of self and rhs if no overflow occurred
  • Err(SafeMathError::Overflow) - If the addition would overflow

§Examples

use safe_math::{SafeAdd, SafeMathError};

let a: u8 = 250;
let b: u8 = 5;

// Safe addition that works
assert_eq!(a.safe_add(b), Ok(255));

// Safe addition that detects overflow
let c: u8 = 251;
assert_eq!(a.safe_add(c), Err(SafeMathError::Overflow));

§See also

  • SafeMathOps - Combined trait for all safe arithmetic operations
  • SafeMathError - Error type returned on arithmetic failures

Required Methods§

Source

fn safe_add(self, rhs: Self) -> Result<Self, SafeMathError>

Performs safe addition with overflow checking.

§Arguments
  • rhs - Right-hand side operand.
§Returns
  • Ok(result) - The sum of self and rhs if no overflow occurred
  • Err(SafeMathError::Overflow) - If the addition would overflow

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl SafeAdd for f32

Source§

fn safe_add(self, rhs: Self) -> Result<Self, SafeMathError>

Performs safe safe_add for f32.

Used internally by the #[safe_math] macro during expansion. Checks for finite results to prevent infinity/NaN propagation.

§Arguments
  • self - First operand.
  • rhs - Second operand.
§Returns

Ok(result) on success, Err(SafeMathError::InfiniteOrNaN) on error.

Source§

impl SafeAdd for f64

Source§

fn safe_add(self, rhs: Self) -> Result<Self, SafeMathError>

Performs safe safe_add for f64.

Used internally by the #[safe_math] macro during expansion. Checks for finite results to prevent infinity/NaN propagation.

§Arguments
  • self - First operand.
  • rhs - Second operand.
§Returns

Ok(result) on success, Err(SafeMathError::InfiniteOrNaN) on error.

Implementors§

Source§

impl<T> SafeAdd for T
where T: IsSafeAdd + Add<Output = T> + Copy,