Re: [PATCH v3 2/5] rust: mem: add DropGuard

From: Gary Guo

Date: Sat Sep 26 2026 - 19:53:26 EST


On Sat Sep 26, 2026 at 6:33 PM BST, Mohamed Osama wrote:
> Add DropGuard to the Rust kernel memory module.
>
> DropGuard runs a FnOnce callback when the guard is dropped and provides
> dismiss() to take ownership of the wrapped value without running the
> cleanup callback.
>
> This follows the upstream core::mem::DropGuard API, which is being
> stabilized in Rust.
>
> Keep ScopeGuard for existing users rather than changing its API in this
> patch. Migrate the existing users that can use DropGuard to establish
> the kernel API alongside the upstream Rust API.

If you're vendoring code from standard library, please put them in std_vendor
and have it re-exported from kernel::mem please.

Also, if the code is taken directly from std with only minor changes (e.g.
removing const trait stuff and add `#[inline]`), then I don't think we need the
kunit tests.

Best,
Gary

>
> Signed-off-by: Mohamed Osama <mohamed.osama189110@xxxxxxxxx>
> ---
> rust/kernel/mem.rs | 121 +++++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 121 insertions(+)
>
> diff --git a/rust/kernel/mem.rs b/rust/kernel/mem.rs
> index f2d4cdf87d00..e7a84d15f3b3 100644
> --- a/rust/kernel/mem.rs
> +++ b/rust/kernel/mem.rs
> @@ -4,6 +4,93 @@
>
> use crate::prelude::*;
>
> +use core::mem::ManuallyDrop;
> +use core::ops::{Deref, DerefMut};
> +
> +/// Wraps a value and runs a closure when dropped.
> +///
> +/// This is useful for running cleanup code when leaving a scope.
> +///
> +/// The [`DropGuard::dismiss`] function can be used to take ownership of the wrapped
> +/// value without running the cleanup function.
> +#[doc(alias = "ScopeGuard")]
> +#[doc(alias = "defer")]
> +pub struct DropGuard<T, F>
> +where
> + F: FnOnce(T),
> +{
> + inner: ManuallyDrop<T>,
> + f: ManuallyDrop<F>,
> +}
> +
> +impl<T, F> DropGuard<T, F>
> +where
> + F: FnOnce(T),
> +{
> + /// Creates a new `DropGuard`.
> + #[inline]
> + #[must_use]
> + pub fn new(inner: T, f: F) -> Self {
> + Self {
> + inner: ManuallyDrop::new(inner),
> + f: ManuallyDrop::new(f),
> + }
> + }
> +
> + /// Consumes the `DropGuard`, returning the wrapped value without
> + /// running the cleanup function.
> + #[inline]
> + pub fn dismiss(guard: Self) -> T {
> + let mut guard = ManuallyDrop::new(guard);
> +
> + // SAFETY: We have taken ownership of the guard and prevent its destructor from running.
> + let value = unsafe { ManuallyDrop::take(&mut guard.inner) };
> +
> + // SAFETY: We have taken ownership of the guard.
> + unsafe { ManuallyDrop::drop(&mut guard.f) };
> +
> + value
> + }
> +}
> +
> +impl<T, F> Deref for DropGuard<T, F>
> +where
> + F: FnOnce(T),
> +{
> + type Target = T;
> +
> + #[inline]
> + fn deref(&self) -> &T {
> + &self.inner
> + }
> +}
> +
> +impl<T, F> DerefMut for DropGuard<T, F>
> +where
> + F: FnOnce(T),
> +{
> + #[inline]
> + fn deref_mut(&mut self) -> &mut T {
> + &mut self.inner
> + }
> +}
> +
> +impl<T, F> Drop for DropGuard<T, F>
> +where
> + F: FnOnce(T),
> +{
> + #[inline]
> + fn drop(&mut self) {
> + // SAFETY: `DropGuard` is in the process of being dropped.
> + let inner = unsafe { ManuallyDrop::take(&mut self.inner) };
> +
> + // SAFETY: `DropGuard` is in the process of being dropped.
> + let f = unsafe { ManuallyDrop::take(&mut self.f) };
> +
> + f(inner);
> + }
> +}
> +
> /// Transmute between two types.
> ///
> /// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this
> @@ -232,3 +319,37 @@ unsafe impl AsReprMut for $signed {}
> // `usize` is not normalized to particular integer for portability.
> usize isize,
> }
> +
> +#[cfg(CONFIG_RUST_DROP_GUARD_KUNIT_TEST)]
> +#[macros::kunit_tests(rust_drop_guard)]
> +mod tests {
> + use super::*;
> +
> + #[test]
> + fn test_drop_runs_cleanup() {
> + let mut cleaned = false;
> +
> + {
> + let _guard = DropGuard::new(42, |value| {
> + assert_eq!(value, 42);
> + cleaned = true;
> + });
> + }
> +
> + assert!(cleaned);
> + }
> +
> + #[test]
> + fn test_dismiss_returns_value_without_cleanup() {
> + let mut cleaned = false;
> +
> + let guard = DropGuard::new(42, |_| {
> + cleaned = true;
> + });
> +
> + let value = DropGuard::dismiss(guard);
> +
> + assert_eq!(value, 42);
> + assert!(!cleaned);
> + }
> +}