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
Provenance
- Commit
a1306a2- Tree
8bd3c4d- Author
Johan Andersson <repi@repi.se>- Committer
Johan Andersson <repi@repi.se>- Parent
6fa503d
1 file changed+97 added−0 removed
modified:src/lib.rs+97 added
289 unmodified lines290 return std::result::Result::Err($crate::anyhow!($fmt, $($arg)*));291 };292 }293 294+/// 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]353+macro_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+}365+366 /// 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 implements46 unmodified lines416 417 Error::new_adhoc(message, backtrace)418 }419 }420+421+#[cfg(test)]422+mod 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());430+431+ let v = 1;432+ let f = || {433+ ensure!(v + v == 2, "This is correct, v: {}", v);434+ Ok(())435+ };436+ assert!(f().is_ok());437+438+ let f = || {439+ ensure!(v + v == 1, "This is not correct, v: {}", v);440+ Ok(())441+ };442+ assert!(f().is_err());443+ }444+}