pub fn ensures<T, F, M>(value: T, predicate: F, message: M) -> Result<T>
Expand description
Checks an arbitrary condition expressed in a predicate run against a given value. If the condition is satisfied(read: if the predicate evaluates to true) this function yields the value passed to it. Ergo, it is most useful for checking return values at the end of a function. You must provide an error message in case of failure.
§Examples
Though these example use the crate’s own error type, you can substitute whatever you wish so long as it works.
use runtime_contracts::{ensures, error::RuntimeContractError};
fn add_two(i: i32, j: i32) -> Result<i32, RuntimeContractError> {
ensures(i + j, |sum| *sum > 0, "the sum of i and j must be greater than 0")
}
let eleven_result = add_two(5, 6);
assert!(eleven_result.is_ok());
assert_eq!(eleven_result.unwrap(), 11);
let five_result = add_two(10, -5);
assert!(five_result.is_ok());
assert_eq!(five_result.unwrap(), 5);
// In the below, the output value doesn't satisfy the contract since `5 + - 5 = 5 - 5` is not greater than 0.
assert!(add_two(5, -5).is_err());