Add `ensure!` support

This commit is contained in:
Gavrilikhin Daniil 2023-05-06 22:58:08 +08:00
parent 287ffc54ac
commit 4f0bc3e8d3
1 changed files with 18 additions and 0 deletions

View File

@ -105,6 +105,19 @@ macro_rules! bail {
/// # Ok(())
/// # }
/// ```
///
/// ```
/// use miette::{ensure, Result, Severity};
///
/// fn divide(x: f64, y: f64) -> Result<f64> {
/// ensure!(
/// y.abs() >= 1e-3,
/// "dividing by value close to 0",
/// severity = Severity::Warning
/// );
/// Ok(x / y)
/// }
/// ```
#[macro_export]
macro_rules! ensure {
($cond:expr, $msg:literal $(,)?) => {
@ -117,6 +130,11 @@ macro_rules! ensure {
return $crate::private::Err($crate::miette!($err));
}
};
($cond:expr, $fmt:expr $(, $key:ident = $value:expr)* $(,)?) => {
if !$cond {
return $crate::private::Err($crate::miette!($fmt, $($key = $value),*));
}
};
($cond:expr, $fmt:expr, $($arg:tt)*) => {
if !$cond {
return $crate::private::Err($crate::miette!($fmt, $($arg)*));