referrerpolicy=no-referrer-when-downgrade

Trait sp_runtime::traits::EnsureFixedPointNumber

pub trait EnsureFixedPointNumber: FixedPointNumber {
    // Provided methods
    fn ensure_from_rational<N, D>(n: N, d: D) -> Result<Self, ArithmeticError>
       where N: FixedPointOperand,
             D: FixedPointOperand { ... }
    fn ensure_mul_int<N>(self, n: N) -> Result<N, ArithmeticError>
       where N: FixedPointOperand { ... }
    fn ensure_div_int<D>(self, d: D) -> Result<D, ArithmeticError>
       where D: FixedPointOperand { ... }
}
Expand description

Extends FixedPointNumber with the Ensure family functions.

Provided Methods§

fn ensure_from_rational<N, D>(n: N, d: D) -> Result<Self, ArithmeticError>

Creates self from a rational number. Equal to n / d.

Returns ArithmeticError if d == 0 or n / d exceeds accuracy.

Similar to FixedPointNumber::checked_from_rational() but returning an ArithmeticError error.

use sp_arithmetic::{traits::EnsureFixedPointNumber, ArithmeticError, FixedI64};

fn extrinsic_zero() -> Result<(), ArithmeticError> {
    FixedI64::ensure_from_rational(1, 0)?;
    Ok(())
}

fn underflow() -> Result<(), ArithmeticError> {
    FixedI64::ensure_from_rational(i64::MAX, -1)?;
    Ok(())
}

assert_eq!(extrinsic_zero(), Err(ArithmeticError::DivisionByZero));
assert_eq!(underflow(), Err(ArithmeticError::Underflow));

fn ensure_mul_int<N>(self, n: N) -> Result<N, ArithmeticError>

Ensure multiplication for integer type N. Equal to self * n.

Returns ArithmeticError if the result does not fit in N.

Similar to FixedPointNumber::checked_mul_int() but returning an ArithmeticError error.

use sp_arithmetic::{traits::EnsureFixedPointNumber, ArithmeticError, FixedI64};

fn overflow() -> Result<(), ArithmeticError> {
    FixedI64::from(i64::MAX).ensure_mul_int(2)?;
    Ok(())
}

fn underflow() -> Result<(), ArithmeticError> {
    FixedI64::from(i64::MAX).ensure_mul_int(-2)?;
    Ok(())
}

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

fn ensure_div_int<D>(self, d: D) -> Result<D, ArithmeticError>

Ensure division for integer type N. Equal to self / d.

Returns ArithmeticError if the result does not fit in N or d == 0.

Similar to FixedPointNumber::checked_div_int() but returning an ArithmeticError error.

use sp_arithmetic::{traits::EnsureFixedPointNumber, ArithmeticError, FixedI64};

fn extrinsic_zero() -> Result<(), ArithmeticError> {
    FixedI64::from(1).ensure_div_int(0)?;
    Ok(())
}

fn overflow() -> Result<(), ArithmeticError> {
    FixedI64::from(i64::MIN).ensure_div_int(-1)?;
    Ok(())
}

assert_eq!(extrinsic_zero(), Err(ArithmeticError::DivisionByZero));
assert_eq!(overflow(), Err(ArithmeticError::Overflow));

Object Safety§

This trait is not object safe.

Implementors§