From e1d1fe7fda34eb8bb7f1ba722c840008e27fcefe Mon Sep 17 00:00:00 2001 From: Julian Orth Date: Sat, 7 Sep 2024 17:02:28 +0200 Subject: [PATCH] util: add OnDrop2 for non-copy closures --- src/utils/on_drop.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/utils/on_drop.rs b/src/utils/on_drop.rs index a7a12d79..15557f0a 100644 --- a/src/utils/on_drop.rs +++ b/src/utils/on_drop.rs @@ -1,4 +1,4 @@ -use std::mem; +use std::{mem, mem::ManuallyDrop}; pub struct OnDrop(pub F) where @@ -15,3 +15,34 @@ impl Drop for OnDrop { (self.0)(); } } + +pub struct OnDrop2 +where + F: FnOnce(), +{ + f: ManuallyDrop, +} + +impl OnDrop2 { + #[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 Drop for OnDrop2 { + fn drop(&mut self) { + let f = unsafe { ManuallyDrop::take(&mut self.f) }; + f(); + } +}