aboutsummaryrefslogtreecommitdiff
path: root/embassy-hal-common/src/drop.rs
diff options
context:
space:
mode:
Diffstat (limited to 'embassy-hal-common/src/drop.rs')
-rw-r--r--embassy-hal-common/src/drop.rs51
1 files changed, 51 insertions, 0 deletions
diff --git a/embassy-hal-common/src/drop.rs b/embassy-hal-common/src/drop.rs
new file mode 100644
index 000000000..74a484de7
--- /dev/null
+++ b/embassy-hal-common/src/drop.rs
@@ -0,0 +1,51 @@
1use core::mem;
2use core::mem::MaybeUninit;
3
4pub struct OnDrop<F: FnOnce()> {
5 f: MaybeUninit<F>,
6}
7
8impl<F: FnOnce()> OnDrop<F> {
9 pub fn new(f: F) -> Self {
10 Self {
11 f: MaybeUninit::new(f),
12 }
13 }
14
15 pub fn defuse(self) {
16 mem::forget(self)
17 }
18}
19
20impl<F: FnOnce()> Drop for OnDrop<F> {
21 fn drop(&mut self) {
22 unsafe { self.f.as_ptr().read()() }
23 }
24}
25
26/// An explosive ordinance that panics if it is improperly disposed of.
27///
28/// This is to forbid dropping futures, when there is absolutely no other choice.
29///
30/// To correctly dispose of this device, call the [defuse](struct.DropBomb.html#method.defuse)
31/// method before this object is dropped.
32pub struct DropBomb {
33 _private: (),
34}
35
36impl DropBomb {
37 pub fn new() -> Self {
38 Self { _private: () }
39 }
40
41 /// Diffuses the bomb, rendering it safe to drop.
42 pub fn defuse(self) {
43 mem::forget(self)
44 }
45}
46
47impl Drop for DropBomb {
48 fn drop(&mut self) {
49 panic!("boom")
50 }
51}