embassy/embassy-hal-common/src/drop.rs

52 lines
1.1 KiB
Rust
Raw Normal View History

2020-09-22 16:03:43 +00:00
use core::mem;
use core::mem::MaybeUninit;
2023-03-17 10:40:19 +00:00
#[must_use = "to delay the drop handler invokation to the end of the scope"]
pub struct OnDrop<F: FnOnce()> {
f: MaybeUninit<F>,
}
impl<F: FnOnce()> OnDrop<F> {
pub fn new(f: F) -> Self {
2022-06-12 20:15:44 +00:00
Self { f: MaybeUninit::new(f) }
}
pub fn defuse(self) {
mem::forget(self)
}
}
impl<F: FnOnce()> Drop for OnDrop<F> {
fn drop(&mut self) {
unsafe { self.f.as_ptr().read()() }
}
}
2020-09-22 16:03:43 +00:00
2021-03-24 19:36:02 +00:00
/// An explosive ordinance that panics if it is improperly disposed of.
///
/// This is to forbid dropping futures, when there is absolutely no other choice.
///
/// To correctly dispose of this device, call the [defuse](struct.DropBomb.html#method.defuse)
/// method before this object is dropped.
2023-03-17 10:40:19 +00:00
#[must_use = "to delay the drop bomb invokation to the end of the scope"]
2020-09-22 16:03:43 +00:00
pub struct DropBomb {
_private: (),
}
impl DropBomb {
pub fn new() -> Self {
Self { _private: () }
}
2021-03-24 20:21:32 +00:00
2022-01-14 11:48:38 +00:00
/// Defuses the bomb, rendering it safe to drop.
2020-09-22 16:03:43 +00:00
pub fn defuse(self) {
mem::forget(self)
}
}
impl Drop for DropBomb {
fn drop(&mut self) {
panic!("boom")
2020-09-22 16:03:43 +00:00
}
}