Skip to content
Myr

Add ensure macro.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fix #1.

authored by Johan Andersson · committed by Johan Andersson · parent 6fa503d · Browse files · 1 file+97 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+97 added−0 removed

  • other:+97 added−0 removed

1 file+97 added−0 removed

modified:src/lib.rs+97 added
289 unmodified lines
290 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));291 };292}293294/// Return early with an error if a condition is not satisfied.295///296/// This macro is equivalent to `if !condition { return Err(From::from($err)) }`.297///298/// Similar to `assert!`, `ensure!` takes a condition and exits the function299/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`,300/// it does not panic.301///302/// # Example303///304/// ```305/// # use anyhow::{ensure, Result};306/// #307/// #308/// # fn main() -> Result<()> {309/// # let user = 0;310/// # let resource = 0;311/// #312/// ensure!(user == 0, "only user 0 is allowed");313/// # Ok(())314/// # }315/// ```316///317/// ```318/// # use anyhow::{ensure, Result};319/// # use std::fmt::{self, Display};320/// #321/// # #[derive(Debug)]322/// # enum ScienceError {323/// # RecursionLimitExceeded,324/// # }325/// #326/// # impl std::error::Error for ScienceError {}327/// #328/// # impl Display for ScienceError {329/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {330/// # unimplemented!()331/// # }332/// # }333/// #334/// # const MAX_DEPTH: usize = 1;335/// #336/// # const IGNORE: &str = stringify! {337/// #[derive(Error, Debug)]338/// enum ScienceError {339/// #[error(display = "recursion limit exceeded")]340/// RecursionLimitExceeded,341/// ...342/// }343/// # };344///345/// # fn main() -> Result<()> {346/// # let depth = 0;347/// #348/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);349/// # Ok(())350/// # }351/// ```352#[macro_export]353macro_rules! ensure {354 ($cond:expr, $err:expr $(,)?) => {355 if !($cond) {356 return std::result::Result::Err($crate::anyhow!($err));357 }358 };359 ($cond:expr, $fmt:expr, $($arg:tt)*) => {360 if !($cond) {361 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));362 }363 };364}365366/// Construct an ad-hoc error from a string.367///368/// This evaluates to an `Error`. It can take either just a string, or a format369/// string with arguments. It also can take any custom type which implements
46 unmodified lines
416417 Error::new_adhoc(message, backtrace)418 }419}420421#[cfg(test)]422mod test {423 #[test]424 fn ensure() {425 let f = || {426 ensure!(1 + 1 == 2, "This is correct");427 Ok(())428 };429 assert!(f().is_ok());430431 let v = 1;432 let f = || {433 ensure!(v + v == 2, "This is correct, v: {}", v);434 Ok(())435 };436 assert!(f().is_ok());437438 let f = || {439 ensure!(v + v == 1, "This is not correct, v: {}", v);440 Ok(())441 };442 assert!(f().is_err());443 }444}