diff options
| author | Dario Nieuwenhuis <[email protected]> | 2021-09-11 01:53:53 +0200 |
|---|---|---|
| committer | Dario Nieuwenhuis <[email protected]> | 2021-09-11 02:35:35 +0200 |
| commit | ead987245d083b7e6be7158ea3fb63c8a47bf304 (patch) | |
| tree | 2d51b80e3d4fc2670b64cb05af22cc54202a6104 /embassy-hal-common/src/drop.rs | |
| parent | 200f881048a8193c490ff5906ebf320ac98a8331 (diff) | |
embassy: Refactor module structure to remove kitchen-sink `util`.
Diffstat (limited to 'embassy-hal-common/src/drop.rs')
| -rw-r--r-- | embassy-hal-common/src/drop.rs | 51 |
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 @@ | |||
| 1 | use core::mem; | ||
| 2 | use core::mem::MaybeUninit; | ||
| 3 | |||
| 4 | pub struct OnDrop<F: FnOnce()> { | ||
| 5 | f: MaybeUninit<F>, | ||
| 6 | } | ||
| 7 | |||
| 8 | impl<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 | |||
| 20 | impl<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. | ||
| 32 | pub struct DropBomb { | ||
| 33 | _private: (), | ||
| 34 | } | ||
| 35 | |||
| 36 | impl 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 | |||
| 47 | impl Drop for DropBomb { | ||
| 48 | fn drop(&mut self) { | ||
| 49 | panic!("boom") | ||
| 50 | } | ||
| 51 | } | ||
