Skip to main content

ch32_hal/internal/
drop.rs

1#![allow(unused)]
2//! Types for controlling when drop is invoked.
3use core::mem;
4use core::mem::MaybeUninit;
5
6/// A type to delay the drop handler invocation.
7#[must_use = "to delay the drop handler invocation to the end of the scope"]
8pub struct OnDrop<F: FnOnce()> {
9    f: MaybeUninit<F>,
10}
11
12impl<F: FnOnce()> OnDrop<F> {
13    /// Create a new instance.
14    pub fn new(f: F) -> Self {
15        Self { f: MaybeUninit::new(f) }
16    }
17
18    /// Prevent drop handler from running.
19    pub fn defuse(self) {
20        mem::forget(self)
21    }
22}
23
24impl<F: FnOnce()> Drop for OnDrop<F> {
25    fn drop(&mut self) {
26        unsafe { self.f.as_ptr().read()() }
27    }
28}
29
30/// An explosive ordinance that panics if it is improperly disposed of.
31///
32/// This is to forbid dropping futures, when there is absolutely no other choice.
33///
34/// To correctly dispose of this device, call the [defuse](struct.DropBomb.html#method.defuse)
35/// method before this object is dropped.
36#[must_use = "to delay the drop bomb invokation to the end of the scope"]
37pub struct DropBomb {
38    _private: (),
39}
40
41impl DropBomb {
42    /// Create a new instance.
43    pub fn new() -> Self {
44        Self { _private: () }
45    }
46
47    /// Defuses the bomb, rendering it safe to drop.
48    pub fn defuse(self) {
49        mem::forget(self)
50    }
51}
52
53impl Drop for DropBomb {
54    fn drop(&mut self) {
55        panic!("boom")
56    }
57}