Skip to main content

assertables/
assert.rs

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