SafeSub

Trait SafeSub 

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

Safe subtraction operation with underflow checking.

This trait provides checked subtraction that returns a Result instead of panicking or wrapping on underflow.

§Arguments

  • rhs - Right-hand side operand.

§Returns

  • Ok(result) - The difference of self and rhs if no underflow occurred
  • Err(SafeMathError::Overflow) - If the subtraction would underflow

§Examples

use safe_math::{SafeSub, SafeMathError};

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

// Safe subtraction that works
assert_eq!(a.safe_sub(b), Ok(2));

// Safe subtraction that detects underflow
let c: u8 = 10;
assert_eq!(a.safe_sub(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_sub(self, rhs: Self) -> Result<Self, SafeMathError>

Performs safe subtraction with underflow checking.

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

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 SafeSub for f32

Source§

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

Performs safe safe_sub 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 SafeSub for f64

Source§

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

Performs safe safe_sub 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> SafeSub for T
where T: IsSafeSub + Sub<Output = T> + Copy,