feat: OnDropWith helper

This commit is contained in:
Oleksandr Babak 2025-05-15 14:03:21 +02:00 committed by Henrik Tjäder
parent aa4f4ddac8
commit ff3b011cef

View file

@ -1,5 +1,9 @@
//! A drop implementation runner.
use core::ops::{Deref, DerefMut};
pub(crate) struct OnDropWith<T, F: FnMut(&mut T)>(T, F);
/// Runs a closure on drop.
pub struct OnDrop<F: FnOnce()> {
f: core::mem::MaybeUninit<F>,
@ -24,3 +28,33 @@ impl<F: FnOnce()> Drop for OnDrop<F> {
unsafe { self.f.as_ptr().read()() }
}
}
impl<T, F: FnMut(&mut T)> OnDropWith<T, F> {
pub(crate) fn new(value: T, f: F) -> Self {
Self(value, f)
}
pub(crate) fn execute(&mut self) {
(self.1)(&mut self.0);
}
}
impl<T, F: FnMut(&mut T)> Deref for OnDropWith<T, F> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T, F: FnMut(&mut T)> DerefMut for OnDropWith<T, F> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T, F: FnMut(&mut T)> Drop for OnDropWith<T, F> {
fn drop(&mut self) {
self.execute();
}
}