[PATCH v2 2/5] rust: mem: add DropGuard
From: Mohamed Osama
Date: Sat Sep 26 2026 - 12:37:34 EST
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 provides the Rust kernel with a scope guard API matching the
upstream Rust DropGuard interface.
Signed-off-by: Mohamed Osama <mohamed.osama189110@xxxxxxxxx>
---
rust/kernel/mem.rs | 123 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 123 insertions(+)
diff --git a/rust/kernel/mem.rs b/rust/kernel/mem.rs
index f2d4cdf87d00..17807c8e67ac 100644
--- a/rust/kernel/mem.rs
+++ b/rust/kernel/mem.rs
@@ -4,6 +4,95 @@
use crate::prelude::*;
+use core::{
+ mem::ManuallyDrop,
+ 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 +321,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);
+ }
+}
--
2.43.0