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