Skip to content

Commit 1157c24

Browse files
committed
Add ScopeGuard to optionally run cleanup closures.
Signed-off-by: Wedson Almeida Filho <[email protected]>
1 parent 7c23865 commit 1157c24

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub mod user_ptr;
7777
pub use build_error::build_error;
7878

7979
pub use crate::error::{Error, Result};
80-
pub use crate::types::Mode;
80+
pub use crate::types::{Mode, ScopeGuard};
8181

8282
/// Page size defined in terms of the `PAGE_SHIFT` macro from C.
8383
///

rust/kernel/types.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,33 @@ impl<T: PointerWrapper + Deref> PointerWrapper for Pin<T> {
9191
Pin::new_unchecked(T::from_pointer(p))
9292
}
9393
}
94+
95+
/// Runs a cleanup function/closure when dropped.
96+
///
97+
/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
98+
pub struct ScopeGuard<T: FnOnce()> {
99+
cleanup_func: Option<T>,
100+
}
101+
102+
impl<T: FnOnce()> ScopeGuard<T> {
103+
/// Creates a new cleanup object with the given cleanup function.
104+
pub fn new(cleanup_func: T) -> Self {
105+
Self {
106+
cleanup_func: Some(cleanup_func),
107+
}
108+
}
109+
110+
/// Prevents the cleanup function from running.
111+
pub fn dismiss(mut self) {
112+
self.cleanup_func.take();
113+
}
114+
}
115+
116+
impl<T: FnOnce()> Drop for ScopeGuard<T> {
117+
fn drop(&mut self) {
118+
// Run the cleanup function if one is still present.
119+
if let Some(cleanup) = self.cleanup_func.take() {
120+
cleanup();
121+
}
122+
}
123+
}

0 commit comments

Comments
 (0)