http_problem/
macros.rs

1/// Return early with an [`AssertionError`] if a condition is not satisfied.
2///
3/// This macro is equivalent to [`assert!`], but returns a [`Problem`] instead
4/// of panicking.
5///
6/// [`AssertionError`]: crate::prelude::AssertionError
7/// [`Problem`]: crate::Problem
8#[macro_export]
9macro_rules! ensure {
10    ($check:expr, $msg:literal $(,)?) => {
11        if !$check {
12            return Err($crate::Problem::from($crate::prelude::AssertionError::new_static($msg)));
13        }
14    };
15    ($check:expr, $($arg:tt)+) => {
16        if !$check {
17            let msg = format!($($arg)+);
18            return Err($crate::Problem::from($crate::prelude::AssertionError::new(msg)));
19        }
20    }
21}
22
23/// Return early with an [`UnprocessableEntity`] if a condition is not
24/// satisfied.
25///
26/// [`UnprocessableEntity`]: crate::http::UnprocessableEntity
27#[macro_export]
28macro_rules! requires {
29    ($check:expr, $msg:literal $(,)?) => {
30        if !$check {
31            return Err($crate::prelude::http::unprocessable($msg));
32        }
33    };
34    ($check:expr, $($arg:tt)+) => {
35        if !$check {
36            return Err($crate::prelude::http::unprocessable(format!($($arg)+)));
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    #[test]
44    fn test_ensure() {
45        fn inner(cond: bool) -> crate::Result<()> {
46            crate::ensure!(cond, "assertion");
47
48            Ok(())
49        }
50
51        assert!(inner(true).is_ok());
52
53        let err = inner(false).unwrap_err();
54        assert!(err.is::<crate::prelude::AssertionError>());
55    }
56}