Always-assert: recoverable assertions for Rust

https://crates.io/crates/always-assert

A version of assert macros inspired by The Use Of assert() In SQLite

if never!(impossible_condition) {
    // The impossible happened 💔
    // This would have panicked in debug.
    // in release we get a chance for best-effort recovery.
    return None;
}

This is useful for long-running applications, which can't just printf("Sucks to be you"); exit(666) if things go south. I am somewhat embarrassed that that it took me so long to realize this pattern exists: seems obvious in retrospect!

6 Likes

It would be nice to have #[must_use] on that, so it's not just used as a shorthand for debug_assert, but I guess you'd need stable expression attributes.

2 Likes

#[doc(hidden)] #[must_use] pub fn __use_me<T>(t: T) -> T { t } would work, but I don't think that would be good -- in rust-analyzer a significant fraction of cases require a do-nothing recovery.

If you're not doing any recovery, shouldn't you use debug_assert?

That won't log::error in release (which always-assert does via opt in). But other than that, yeah, debug assert would work.

1 Like

A variant invocation, for people who like to live dangerously:

if never!(impossible_condition) {
    unsafe { unreachable_unchecked() };
}

This reminds me of On Error Resume Next from Visual Basic. But hopefully less of a hazard.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.