Skip to content

Commit

Permalink
Merge pull request #129 from dtolnay/ensure
Browse files Browse the repository at this point in the history
1-argument `ensure!`
  • Loading branch information
dtolnay committed Dec 6, 2020
2 parents 0c0e41f + 6161f7d commit cb57a41
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/macros.rs
Expand Up @@ -113,6 +113,9 @@ macro_rules! bail {
/// ```
#[macro_export]
macro_rules! ensure {
($cond:expr $(,)?) => {
$crate::ensure!($cond, concat!("Condition failed: `", stringify!($cond), "`"))
};
($cond:expr, $msg:literal $(,)?) => {
if !$cond {
return $crate::private::Err($crate::anyhow!($msg));
Expand Down
9 changes: 9 additions & 0 deletions tests/test_macros.rs
Expand Up @@ -32,4 +32,13 @@ 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`",
);
}

0 comments on commit cb57a41

Please sign in to comment.