From ff3b011cef0ca6e5f77cb1112940337e913ca957 Mon Sep 17 00:00:00 2001 From: Oleksandr Babak Date: Thu, 15 May 2025 14:03:21 +0200 Subject: [PATCH] feat: `OnDropWith` helper --- rtic-common/src/dropper.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/rtic-common/src/dropper.rs b/rtic-common/src/dropper.rs index a4b4d159274..37c289dca57 100644 --- a/rtic-common/src/dropper.rs +++ b/rtic-common/src/dropper.rs @@ -1,5 +1,9 @@ //! A drop implementation runner. +use core::ops::{Deref, DerefMut}; + +pub(crate) struct OnDropWith(T, F); + /// Runs a closure on drop. pub struct OnDrop { f: core::mem::MaybeUninit, @@ -24,3 +28,33 @@ impl Drop for OnDrop { unsafe { self.f.as_ptr().read()() } } } + +impl OnDropWith { + pub(crate) fn new(value: T, f: F) -> Self { + Self(value, f) + } + + pub(crate) fn execute(&mut self) { + (self.1)(&mut self.0); + } +} + +impl Deref for OnDropWith { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for OnDropWith { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Drop for OnDropWith { + fn drop(&mut self) { + self.execute(); + } +}