1
0
Fork 0
forked from wry/wry

util: add OnDrop2 for non-copy closures

This commit is contained in:
Julian Orth 2024-09-07 17:02:28 +02:00
parent 69c0cf4031
commit e1d1fe7fda

View file

@ -1,4 +1,4 @@
use std::mem;
use std::{mem, mem::ManuallyDrop};
pub struct OnDrop<F>(pub F)
where
@ -15,3 +15,34 @@ impl<F: FnMut() + Copy> Drop for OnDrop<F> {
(self.0)();
}
}
pub struct OnDrop2<F>
where
F: FnOnce(),
{
f: ManuallyDrop<F>,
}
impl<F: FnOnce()> OnDrop2<F> {
#[expect(dead_code)]
pub fn new(f: F) -> Self {
Self {
f: ManuallyDrop::new(f),
}
}
#[expect(dead_code)]
pub fn forget(mut self) {
unsafe {
ManuallyDrop::drop(&mut self.f);
}
mem::forget(self);
}
}
impl<F: FnOnce()> Drop for OnDrop2<F> {
fn drop(&mut self) {
let f = unsafe { ManuallyDrop::take(&mut self.f) };
f();
}
}