Skip to content

Instantly share code, notes, and snippets.

@LunNova
Last active July 1, 2024 04:47
Show Gist options
  • Save LunNova/b3f9610a386d93f0529af12122083b41 to your computer and use it in GitHub Desktop.
Save LunNova/b3f9610a386d93f0529af12122083b41 to your computer and use it in GitHub Desktop.
/// Guards a scope against unwinding, calling a handler if unwinding occurs.
///
/// - Handler gets no panic info; limited to `Fn()`
/// - Not reentrant; handler panics may cause program abort
/// - Intended for single scope; don't store or share
/// - Ineffective with panic=abort
pub struct UnwindDetector<T: Fn()> {
handler: T,
}
impl<T: Fn()> UnwindDetector<T> {
/// Creates a new detector. Handler runs if dropped during panic.
pub fn new(handler: T) -> Self {
Self { handler }
}
}
impl<T: Fn()> Drop for UnwindDetector<T> {
fn drop(&mut self) {
if std::thread::panicking() {
(self.handler)()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment