use core::{cell::UnsafeCell, mem::ManuallyDrop}; /// A guard that runs a closure when it is dropped. pub struct DropGuard(UnsafeCell>); impl DropGuard where F: FnOnce(), { pub fn new(f: F) -> DropGuard { Self(UnsafeCell::new(ManuallyDrop::new(f))) } } impl Drop for DropGuard where F: FnOnce(), { fn drop(&mut self) { // SAFETY: drop() is called exactly once. unsafe { ManuallyDrop::take(&mut *self.0.get())(); } } } impl From for DropGuard where F: FnOnce(), { fn from(f: F) -> Self { DropGuard::new(f) } }