1use core::ops::{Deref, DerefMut};
4
5pub(crate) struct OnDropWith<T, F: FnMut(&mut T)>(T, F);
6
7pub struct OnDrop<F: FnOnce()> {
9 f: core::mem::MaybeUninit<F>,
10}
11
12impl<F: FnOnce()> OnDrop<F> {
13 pub fn new(f: F) -> Self {
15 Self {
16 f: core::mem::MaybeUninit::new(f),
17 }
18 }
19
20 pub fn defuse(self) {
22 core::mem::forget(self)
23 }
24}
25
26impl<F: FnOnce()> Drop for OnDrop<F> {
27 fn drop(&mut self) {
28 unsafe { self.f.as_ptr().read()() }
29 }
30}
31
32impl<T, F: FnMut(&mut T)> OnDropWith<T, F> {
33 pub(crate) fn new(value: T, f: F) -> Self {
34 Self(value, f)
35 }
36
37 pub(crate) fn execute(&mut self) {
38 (self.1)(&mut self.0);
39 }
40}
41
42impl<T, F: FnMut(&mut T)> Deref for OnDropWith<T, F> {
43 type Target = T;
44
45 fn deref(&self) -> &Self::Target {
46 &self.0
47 }
48}
49
50impl<T, F: FnMut(&mut T)> DerefMut for OnDropWith<T, F> {
51 fn deref_mut(&mut self) -> &mut Self::Target {
52 &mut self.0
53 }
54}
55
56impl<T, F: FnMut(&mut T)> Drop for OnDropWith<T, F> {
57 fn drop(&mut self) {
58 self.execute();
59 }
60}