#assertions #macro #expressing #input #enums #rassert #result-returning

rassert-rs

Simple macro for expressing Result-returning assertions

3 stable releases

3.0.0 Aug 27, 2022
2.0.0 Aug 27, 2022
1.0.0 Mar 30, 2022

#1667 in Rust patterns

Download history 6/week @ 2024-08-27 2/week @ 2024-09-17 21/week @ 2024-09-24 7/week @ 2024-10-01

84 downloads per month
Used in 4 crates (2 directly)

MIT license

6KB
86 lines

rassert

Simple macro for expressing Result-returning assertions and notifying, hard-error assertions (useful for functions where you can't propagate an error upstream so you want to log it).

Usage

use rassert::{rassert, rassert_notify};

enum MyError {
    NotAnswerToLife,
}

struct SomeOutput;

pub fn foo(input: usize) -> Result<SomeOutput, MyError> {
    rassert!(input == 42, MyError::NotAnswerToLife);

    let output = ...;
    Ok(output)
}

pub fn bar(input: usize) {
    rassert_notify!(1 != 1, error!("Well, that's not true."));
    
    println!("Hi everyone"); // Never reached since the above rassert_notify fails and returns
}

Why

Because the alternative is rather ugly and does not obviously express that the expression is a precondition.

enum MyError {
    NotAnswerToLife,
}

struct SomeOutput;

pub fn foo(input: usize) -> Result<SomeOutput, MyError> {
    if input != 42 {
        return Err(MyError::NotAnswerToLife);
    }

    let output = ...;
    Ok(output)
}

I found myself just copy-pasting the same rassert macro over and over in my projects, so might as well put it on Cargo.

No runtime deps