1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
//! Assert a condition is true.
//!
//! * If true, return Result `Ok(())`.
//!
//! * Otherwise, return Result `Err` with a diagnostic message.
//!
//! This macro provides the same statements as [`assert`](macro@assert),
//! except this macro returns a Result, rather than doing a panic.
//!
//! This macro is useful for runtime checks, such as checking parameters,
//! or sanitizing inputs, or handling different results in different ways.
//!
//! # Module macros
//!
//! * [`assert_as_result`](macro.assert_as_result.html)
/// Assert a condition is true.
///
/// * If true, return Result `Ok(())`.
///
/// * Otherwise, return Result `Err` with a diagnostic message.
///
/// This macro provides the same statements as [`assert`](macro@assert),
/// except this macro returns a Result, rather than doing a panic.
///
/// This macro is useful for runtime checks, such as checking parameters,
/// or sanitizing inputs, or handling different results in different ways.
///
/// # Module macros
///
/// * [`assert_as_result`](macro.assert_as_result.html)
///
#[macro_export]
macro_rules! assert_as_result {
($a:expr $(,)?) => {{
if $a {
Ok(())
} else {
Err(format!(
concat!(
"assertion failed: `assert!(condition)`\n",
" condition label: `{}`,\n",
" condition debug: `{:?}`,\n",
),
stringify!($a),
$a,
))
}
}};
}
#[cfg(test)]
mod tests {
#[test]
fn test_assert_as_result_x_success() {
let a = true;
let result = assert_as_result!(a);
assert_eq!(result, Ok(()));
}
#[test]
fn test_assert_as_result_x_failure() {
let a = false;
let result = assert_as_result!(a);
assert_eq!(result.is_err(), true);
let actual = result.unwrap_err();
let expect = concat!(
"assertion failed: `assert!(condition)`\n",
" condition label: `a`,\n",
" condition debug: `false`,\n",
);
assert_eq!(actual, expect);
}
}