Skip to main content

pubhubs/misc/
drop_ext.rs

1/// A [`Bomb`] instance will panic if it is not [`Bomb::diffuse`]d.
2///
3/// Add a [`Bomb`] to your type to make sure that something happens before
4/// the type (and thus bomb) is dropped.
5pub struct Bomb {
6    payload: Option<Box<dyn FnOnce() -> String>>,
7}
8
9impl Bomb {
10    pub fn new(msg: impl FnOnce() -> String + 'static) -> Self {
11        Self {
12            payload: Some(Box::new(msg)),
13        }
14    }
15
16    pub fn diffuse(mut self) {
17        self.payload = None
18    }
19}
20
21impl Drop for Bomb {
22    fn drop(&mut self) {
23        if let Some(msg) = self.payload.take() {
24            let message = (msg)();
25
26            log::error!("{message}");
27
28            if !std::thread::panicking() {
29                panic!("{}", message);
30            }
31        }
32    }
33}