1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! # drop_bomb
//!
//! `drop_bomb` provides two types, `DropBomb` and `DebugDropBomb`,
//! which panic in `drop` with a specified message unless
//! defused. This is useful as a building-block for runtime-checked
//! linear types.
//!
//! For example, one can build a variant of `BufWriter` which enforces
//! handling of errors during flush.
//!
//! ```rust
//! extern crate drop_bomb;
//!
//! use std::io::{Write, BufWriter, Result};
//! use drop_bomb::DropBomb;
//!
//! struct CheckedBufWriter<W: Write> {
//!     inner: BufWriter<W>,
//!     bomb: DropBomb,
//! }
//!
//! impl<W: Write> CheckedBufWriter<W> {
//!     fn new(inner: BufWriter<W>) -> CheckedBufWriter<W> {
//!         let bomb = DropBomb::new(
//!             "CheckedBufWriter must be explicitly closed \
//!              to handle potential errors on flush"
//!         );
//!         CheckedBufWriter { inner, bomb }
//!     }
//!
//!     fn close(mut self) -> Result<()> {
//!         self.bomb.defuse();
//!         self.inner.flush()?;
//!         Ok(())
//!     }
//! }
//! ```
//!
//! ## Notes:
//!
//! * Bombs do nothing if a thread is already panicking.
//! * When `#[cfg(debug_assertions)]` is enabled, `DebugDropBomb` is
//!   an always defused and has a zero size.
use std::borrow::Cow;

#[derive(Debug)]
#[must_use]
pub struct DropBomb(RealBomb);

impl DropBomb {
    pub fn new(msg: impl Into<Cow<'static, str>>) -> DropBomb {
        DropBomb(RealBomb::new(msg.into()))
    }
    pub fn defuse(&mut self) {
        self.set_defused(true)
    }
    pub fn set_defused(&mut self, defused: bool) {
        self.0.set_defused(defused)
    }
    pub fn is_defused(&self) -> bool {
        self.0.is_defused()
    }
}

#[derive(Debug)]
#[must_use]
pub struct DebugDropBomb(DebugBomb);

impl DebugDropBomb {
    pub fn new(msg: impl Into<Cow<'static, str>>) -> DebugDropBomb {
        DebugDropBomb(DebugBomb::new(msg.into()))
    }
    pub fn defuse(&mut self) {
        self.set_defused(true)
    }
    pub fn set_defused(&mut self, defused: bool) {
        self.0.set_defused(defused)
    }
    pub fn is_defused(&self) -> bool {
        self.0.is_defused()
    }
}

#[cfg(debug_assertions)]
type DebugBomb = RealBomb;
#[cfg(not(debug_assertions))]
type DebugBomb = FakeBomb;

#[derive(Debug)]
struct RealBomb {
    msg: Cow<'static, str>,
    defused: bool,
}

impl RealBomb {
    fn new(msg: Cow<'static, str>) -> RealBomb {
        RealBomb {
            msg: msg.into(),
            defused: false,
        }
    }
    fn set_defused(&mut self, defused: bool) {
        self.defused = defused
    }
    fn is_defused(&self) -> bool {
        self.defused
    }
}

impl Drop for RealBomb {
    fn drop(&mut self) {
        if !self.defused && !::std::thread::panicking() {
            panic!("{}", self.msg)
        }
    }
}

#[derive(Debug)]
#[cfg(not(debug_assertions))]
struct FakeBomb {}

#[cfg(not(debug_assertions))]
impl FakeBomb {
    fn new(_msg: Cow<'static, str>) -> FakeBomb {
        FakeBomb {}
    }
    fn set_defused(&mut self, _defused: bool) {}
    fn is_defused(&self) -> bool {
        true
    }
}

#[cfg(not(debug_assertions))]
impl Drop for FakeBomb {
    fn drop(&mut self) {}
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic(expected = "Kaboom")]
    fn armed_bomb_bombs() {
        let _b = DropBomb::new("Kaboom");
    }

    #[test]
    fn defused_bomb_is_safe() {
        let mut b = DropBomb::new("Kaboom");
        assert!(!b.is_defused());
        b.defuse();
        assert!(b.is_defused());
    }

    #[test]
    #[should_panic(expected = r#"printf("sucks to be you"); exit(666);"#)]
    fn no_double_panics() {
        let _b = DropBomb::new("Kaboom");
        panic!(r#"printf("sucks to be you"); exit(666);"#)
    }

    #[test]
    #[should_panic(expected = "Kaboom")]
    #[cfg(debug_assertions)]
    fn debug_bomb_bombs_if_debug() {
        let _b = DebugDropBomb::new("Kaboom");
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn debug_bomb_bombs_if_debug() {
        let _b = DebugDropBomb::new("Kaboom");
    }

    #[test]
    fn defused_bomb_is_safe_if_debug() {
        let mut b = DebugDropBomb::new("Kaboom");
        #[cfg(debug_assertions)]
        assert!(!b.is_defused());
        #[cfg(not(debug_assertions))]
        assert!(b.is_defused());
        b.defuse();
        assert!(b.is_defused());
    }

    #[test]
    #[should_panic(expected = r#"printf("sucks to be you"); exit(666);"#)]
    fn no_double_panics_if_debug() {
        let _b = DebugDropBomb::new("Kaboom");
        panic!(r#"printf("sucks to be you"); exit(666);"#)
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn debug_bomb_is_zst() {
        assert_eq!(::std::mem::size_of::<DebugDropBomb>(), 0);
    }

    #[test]
    fn check_traits() {
        fn assert_traits<T: ::std::fmt::Debug + Send + Sync>() {}
        assert_traits::<DropBomb>();
        assert_traits::<DebugDropBomb>();
    }
}