0 day streak
rust / expert
Snippet

Transactional Rollback Execution with Custom Scope Guards

In systems programming, ensuring state rollback on function failure or panics is crucial. This snippet implements a scope guard using the `Drop` trait. If a function exits prematurely before `.commit()` is called, the guard automatically restores the state to its original backup value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pub struct RollbackGuard<'a, T: Clone> {
value_ref: &'a mut T,
backup: T,
dismissed: bool,
}
impl<'a, T: Clone> RollbackGuard<'a, T> {
pub fn new(value_ref: &'a mut T) -> Self {
let backup = value_ref.clone();
Self { value_ref, backup, dismissed: false }
}
pub fn commit(mut self) {
self.dismissed = true;
}
}
impl<'a, T: Clone> Drop for RollbackGuard<'a, T> {
fn drop(&mut self) {
if !self.dismissed {
*self.value_ref = self.backup.clone();
}
}
}
Breakdown
1
pub struct RollbackGuard<'a, T: Clone> {
Declares a RAII wrapper taking a mutable reference and backing up the original value.
2
pub fn commit(mut self) {
Dismisses the rollback action, indicating the operation succeeded and state should persist.
3
fn drop(&mut self) {
Destructor logic invoked when scope exits; performs the clone-restore if the operation was not committed.