Skip to content

Commit aa64a6d

Browse files
authored
Merge pull request #19110 from eagr/panic-context
Simplify panic_context
2 parents b636cf9 + 5897755 commit aa64a6d

File tree

1 file changed

+18
-22
lines changed

1 file changed

+18
-22
lines changed

Diff for: crates/stdx/src/panic_context.rs

+18-22
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,42 @@
11
//! A micro-crate to enhance panic messages with context info.
2-
//!
3-
//! FIXME: upstream to <https://github.com/kriomant/panic-context> ?
42
53
use std::{cell::RefCell, panic, sync::Once};
64

7-
pub fn enter(context: String) -> PanicContext {
8-
static ONCE: Once = Once::new();
9-
ONCE.call_once(PanicContext::init);
10-
11-
with_ctx(|ctx| ctx.push(context));
12-
PanicContext { _priv: () }
13-
}
14-
5+
/// Dummy for leveraging RAII cleanup to pop frames.
156
#[must_use]
167
pub struct PanicContext {
8+
// prevent arbitrary construction
179
_priv: (),
1810
}
1911

20-
impl PanicContext {
12+
impl Drop for PanicContext {
13+
fn drop(&mut self) {
14+
with_ctx(|ctx| assert!(ctx.pop().is_some()));
15+
}
16+
}
17+
18+
pub fn enter(frame: String) -> PanicContext {
2119
#[allow(clippy::print_stderr)]
22-
fn init() {
20+
fn set_hook() {
2321
let default_hook = panic::take_hook();
24-
#[allow(deprecated)]
25-
let hook = move |panic_info: &panic::PanicInfo<'_>| {
22+
panic::set_hook(Box::new(move |panic_info| {
2623
with_ctx(|ctx| {
2724
if !ctx.is_empty() {
2825
eprintln!("Panic context:");
2926
for frame in ctx.iter() {
3027
eprintln!("> {frame}\n");
3128
}
3229
}
33-
default_hook(panic_info);
3430
});
35-
};
36-
panic::set_hook(Box::new(hook));
31+
default_hook(panic_info);
32+
}));
3733
}
38-
}
3934

40-
impl Drop for PanicContext {
41-
fn drop(&mut self) {
42-
with_ctx(|ctx| assert!(ctx.pop().is_some()));
43-
}
35+
static SET_HOOK: Once = Once::new();
36+
SET_HOOK.call_once(set_hook);
37+
38+
with_ctx(|ctx| ctx.push(frame));
39+
PanicContext { _priv: () }
4440
}
4541

4642
fn with_ctx(f: impl FnOnce(&mut Vec<String>)) {

0 commit comments

Comments
 (0)