util: add OnDrop2 for non-copy closures
This commit is contained in:
parent
69c0cf4031
commit
e1d1fe7fda
1 changed files with 32 additions and 1 deletions
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue