//! A drop implementation runner. use core::ops::{Deref, DerefMut}; pub(crate) struct OnDropWith(T, F); /// Runs a closure on drop. pub struct OnDrop { f: core::mem::MaybeUninit, } impl OnDrop { /// Make a new droppper given a closure. pub fn new(f: F) -> Self { Self { f: core::mem::MaybeUninit::new(f), } } /// Make it not run drop. pub fn defuse(self) { core::mem::forget(self) } } impl Drop for OnDrop { fn drop(&mut self) { unsafe { self.f.as_ptr().read()() } } } impl OnDropWith { pub(crate) fn new(value: T, f: F) -> Self { Self(value, f) } pub(crate) fn execute(&mut self) { (self.1)(&mut self.0); } } impl Deref for OnDropWith { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for OnDropWith { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Drop for OnDropWith { fn drop(&mut self) { self.execute(); } }