Skip to content
Myr

Merge pull request #4 from EmbarkStudios/ensure

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

Add ensure macro

authored by David Tolnay · committed by GitHub · parents dcb6b79, a1306a2 · 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
292 unmodified lines
293 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));294 };295}296297/// Return early with an error if a condition is not satisfied.298///299/// This macro is equivalent to `if !condition { return Err(From::from($err)) }`.300///301/// Similar to `assert!`, `ensure!` takes a condition and exits the function302/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`,303/// it does not panic.304///305/// # Example306///307/// ```308/// # use anyhow::{ensure, Result};309/// #310/// #311/// # fn main() -> Result<()> {312/// # let user = 0;313/// # let resource = 0;314/// #315/// ensure!(user == 0, "only user 0 is allowed");316/// # Ok(())317/// # }318/// ```319///320/// ```321/// # use anyhow::{ensure, Result};322/// # use std::fmt::{self, Display};323/// #324/// # #[derive(Debug)]325/// # enum ScienceError {326/// # RecursionLimitExceeded,327/// # }328/// #329/// # impl std::error::Error for ScienceError {}330/// #331/// # impl Display for ScienceError {332/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {333/// # unimplemented!()334/// # }335/// # }336/// #337/// # const MAX_DEPTH: usize = 1;338/// #339/// # const IGNORE: &str = stringify! {340/// #[derive(Error, Debug)]341/// enum ScienceError {342/// #[error(display = "recursion limit exceeded")]343/// RecursionLimitExceeded,344/// ...345/// }346/// # };347///348/// # fn main() -> Result<()> {349/// # let depth = 0;350/// #351/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);352/// # Ok(())353/// # }354/// ```355#[macro_export]356macro_rules! ensure {357 ($cond:expr, $err:expr $(,)?) => {358 if !($cond) {359 return std::result::Result::Err($crate::anyhow!($err));360 }361 };362 ($cond:expr, $fmt:expr, $($arg:tt)*) => {363 if !($cond) {364 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));365 }366 };367}368369/// Construct an ad-hoc error from a string.370///371/// This evaluates to an `Error`. It can take either just a string, or a format372/// string with arguments. It also can take any custom type which implements
46 unmodified lines
419420 Error::new_adhoc(message, backtrace)421 }422}423424#[cfg(test)]425mod test {426 #[test]427 fn ensure() {428 let f = || {429 ensure!(1 + 1 == 2, "This is correct");430 Ok(())431 };432 assert!(f().is_ok());433434 let v = 1;435 let f = || {436 ensure!(v + v == 2, "This is correct, v: {}", v);437 Ok(())438 };439 assert!(f().is_ok());440441 let f = || {442 ensure!(v + v == 1, "This is not correct, v: {}", v);443 Ok(())444 };445 assert!(f().is_err());446 }447}