From 75f4b4f773d729f91828e5aae579928143ee3d55 Mon Sep 17 00:00:00 2001 From: sharnoff Date: Fri, 23 Sep 2022 16:26:10 -0700 Subject: [PATCH] Add 1-argument `ensure!($expr)` --- src/macros.rs | 5 +++++ tests/test_macros.rs | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/src/macros.rs b/src/macros.rs index 792a646..50c1dbf 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -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)); diff --git a/tests/test_macros.rs b/tests/test_macros.rs index abcc3c9..2a6d92f 100644 --- a/tests/test_macros.rs +++ b/tests/test_macros.rs @@ -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]