dtolnay / dtolnay/no-panic

Exempt block within function from panic check

Open
#76 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
1.2k
Forks
20
PR merge metrics
No merged PRs in 30d

Description

This is a follow-up to https://github.com/dtolnay/no-panic/issues/16: I came up with a macro that makes exempting blocks very easy and I figured I'd share. Example usage:

```rust
#[cfg_attr(feature = "_no_panic", no_panic::no_panic)]
fn foo() -> Vec {
let v = exempt_panics!({
vec![0; 42] // Allocation may panic
});
v
}
```

Macro Definition:
```rust
// With the `_no_panic` feature enabled, `exempt_panics!` uses an `extern "C"` wrapper
// to hide the panic from the no_panic macro.
#[cfg(feature = "_no_panic")]
macro_rules! exempt_panics {
($block:block) => {{
#[allow(improper_ctypes_definitions)]
#[inline(always)]
extern "C" fn __exempt_wrapper R>(f: F) -> R {
f()
}

__exempt_wrapper(|| $block)
}};
}

// With the `_no_panic` feature disabled, `exempt_panics!` does nothing.
#[cfg(not(feature = "_no_panic"))]
macro_rules! exempt_panics {
($block:block) => {
$block
};
}

pub(crate) use exempt_panics;
```

Thank you for building `no_panic`! 😃

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.