SafeDiv

Trait SafeDiv 

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

Safe division operation with division-by-zero checking.

This trait provides checked division that returns a Result instead of panicking when attempting to divide by zero. It also handles potential overflow cases for signed integer division.

§Arguments

  • rhs - Right-hand side operand (divisor).

§Returns

  • Ok(result) - The quotient of self divided by rhs if division is valid
  • Err(SafeMathError::DivisionByZero) - If rhs is zero
  • Err(SafeMathError::Overflow) - If the division would overflow (e.g., MIN/-1 for signed integers)

§Examples

use safe_math::{SafeDiv, SafeMathError};

let a: u8 = 10;
let b: u8 = 2;

// Safe division that works
assert_eq!(a.safe_div(b), Ok(5));

// Safe division that detects division by zero
let zero: u8 = 0;
assert_eq!(a.safe_div(zero), Err(SafeMathError::DivisionByZero));

§See also

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

Required Methods§

Source

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

Performs safe division with division-by-zero checking.

§Arguments
  • rhs - Right-hand side operand (divisor).
§Returns
  • Ok(result) - The quotient of self divided by rhs if division is valid
  • Err(SafeMathError::DivisionByZero) - If rhs is zero
  • Err(SafeMathError::Overflow) - If the division 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 SafeDiv for f32

Source§

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

Performs safe safe_div 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 SafeDiv for f64

Source§

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

Performs safe safe_div 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> SafeDiv for T
where T: IsSafeDiv + Div<Output = T> + Copy,