Skip to content

Commit

Permalink
Add 1-argument ensure!($expr)
Browse files Browse the repository at this point in the history
  • Loading branch information
sharnoff authored and thenorili committed Nov 21, 2023
1 parent 949e845 commit ec98ce3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
5 changes: 5 additions & 0 deletions eyre/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ macro_rules! bail {
/// ```
#[macro_export]
macro_rules! ensure {
($cond:expr $(,)?) => {
if !$cond {
$crate::ensure!($cond, concat!("Condition failed: `", stringify!($cond), "`"))
}
};
($cond:expr, $msg:literal $(,)?) => {
if !$cond {
return $crate::private::Err($crate::eyre!($msg));
Expand Down
9 changes: 9 additions & 0 deletions eyre/tests/test_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ fn test_ensure() {
Ok(())
};
assert!(f().is_err());

let f = || {
ensure!(v + v == 1);
Ok(())
};
assert_eq!(
f().unwrap_err().to_string(),
"Condition failed: `v + v == 1`",
);
}

#[test]
Expand Down

0 comments on commit ec98ce3

Please sign in to comment.