homestar_invocation/
macros.rs

1//! Macros for cross-crate export.
2
3/// Return early with an error.
4///
5/// Modelled after [anyhow::bail].
6///
7/// # Example
8///
9/// ```
10/// use homestar_invocation::{bail, Error, Unit};
11///
12/// fn has_permission(user: usize, resource: usize) -> bool {
13///      true
14/// }
15///
16/// # fn main() -> Result<(), Error<Unit>> {
17/// #     let user = 0;
18/// #     let resource = 0;
19/// #
20///
21/// if !has_permission(user, resource) {
22///     bail!(Error::Unknown);
23/// }
24///
25/// #    Ok(())
26/// # }
27/// ```
28#[macro_export]
29macro_rules! bail {
30    ($e:expr) => {
31        return Err($e);
32    };
33}
34
35/// Return early with an error if a condition is not satisfied.
36///
37/// Analogously to `assert!`, `ensure!` takes a condition and exits the function
38/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
39/// rather than panicking.
40///
41/// Modelled after [anyhow::ensure].
42///
43/// # Example
44///
45/// ```
46/// use homestar_invocation::{ensure, Error, Unit};
47///
48/// #
49/// # fn main() -> Result<(), Error<Unit>> {
50/// #     let user = 1;
51/// #
52/// ensure!(
53///     user < 2,
54///     Error::ConditionNotMet(
55///         "only user 0 and 1 are allowed".to_string()
56///     )
57/// );
58/// #     Ok(())
59/// # }
60/// ```
61#[macro_export(local_inner_macros)]
62macro_rules! ensure {
63    ($cond:expr, $e:expr) => {
64        if !($cond) {
65            bail!($e);
66        }
67    };
68}