ensure_with

Macro ensure_with 

Source
macro_rules! ensure_with {
    ($cond: expr, $fmt:literal) => { ... };
    ($cond: expr, $str: expr) => { ... };
    ($cond: expr, $fmt:literal, $($arg:tt)+) => { ... };
}
Expand description

Helper macro for ensuring a boolean condition while returning early with a newly constructed SimpleError if the condition is false. Can be used in functions that return Result<_, E> where E: From<SimpleError> (e.g. SimpleError or Box<dyn Error>).

ยงExamples

use simple_error::{SimpleError, ensure_with};
use std::error::Error;

fn ensure_block(cond: bool, s: &str) -> Result<(), SimpleError> {
    ensure_with!(cond, s);
    Ok(())
}

// Above is equivalent to below.

fn ensure_block_equivalent(cond: bool, s: &str) -> Result<(), SimpleError> {
    if !cond {
        return Err(SimpleError::new(s));
    }
    Ok(())
}

// Use a format string
fn ensure_block_format(cond: bool, s: &str) -> Result<(), SimpleError> {
    ensure_with!(cond, "with {}", s);
    Ok(())
}

// Use a format string to a boxed error
fn ensure_block_format_to_box_error(cond: bool, s: &str) -> Result<(), Box<dyn Error>> {
    ensure_with!(cond, "with {}", s);
    Ok(())
}