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
/// Return early with an [`AssertionError`] if a condition is not satisfied.
///
/// This macro is equivalent to [`assert!`], but returns a [`Problem`] instead
/// of panicking.
///
/// [`AssertionError`]: crate::prelude::AssertionError
/// [`Problem`]: crate::Problem
#[macro_export]
macro_rules! ensure {
    ($check:expr, $msg:literal $(,)?) => {
        if !$check {
            return Err($crate::Problem::from($crate::prelude::AssertionError::new_static($msg)));
        }
    };
    ($check:expr, $($arg:tt)+) => {
        if !$check {
            let msg = format!($($arg)+);
            return Err($crate::Problem::from($crate::prelude::AssertionError::new(msg)));
        }
    }
}

/// Return early with an [`UnprocessableEntity`] if a condition is not
/// satisfied.
///
/// [`UnprocessableEntity`]: crate::http::UnprocessableEntity
#[macro_export]
macro_rules! requires {
    ($check:expr, $msg:literal $(,)?) => {
        if !$check {
            return Err($crate::prelude::http::unprocessable($msg));
        }
    };
    ($check:expr, $($arg:tt)+) => {
        if !$check {
            return Err($crate::prelude::http::unprocessable(format!($($arg)+)));
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_ensure() {
        fn inner(cond: bool) -> crate::Result<()> {
            crate::ensure!(cond, "assertion");

            Ok(())
        }

        assert!(inner(true).is_ok());

        let err = inner(false).unwrap_err();
        assert!(err.is::<crate::prelude::AssertionError>());
    }
}