3 个稳定版本
1.2.0 | 2023年3月11日 |
---|---|
1.1.0 | 2022年9月9日 |
1.0.0 | 2021年3月3日 |
#221 在 无标准库
219 每月下载量
10KB
129 行
范围守卫
简单的 RAII 范围守卫
功能
std
- 启用异步作用域,以便在 future 完成时运行析构函数,即使它崩溃。
lib.rs
:
简单的 RAII 范围守卫
使用方法
无参数守卫
use scope_guard::scope_guard;
let mut is_run = false;
{
scope_guard!(|| {
is_run = true;
});
}
assert!(is_run);
单个参数守卫
use scope_guard::scope_guard;
fn do_stuff(val: &mut u32) {
let old_val = *val;
let mut val = scope_guard!(|val| {
*val = old_val;
}, val);
**val += 1; //Double * to deref &mut u32
let is_ok = false;//doing some computations
if is_ok {
val.forget();
}
}
let mut val = 0;
do_stuff(&mut val);
assert_eq!(val, 0);
let mut guard = scope_guard!(|val| {
*val = 1;
}, &mut val);
drop(guard);
assert_eq!(val, 1);
堆栈析构函数调用
use scope_guard::scope_guard;
fn do_stuff(val: &mut u32) {
let old_value = *val;
let val = scope_guard!(|val| {
assert_eq!(*val, old_value);
//Do nothing
}, val);
let mut val = val.stack(|val| {
**val = old_value;
});
**val += 1; //Double * to deref &mut u32
}
let mut val = 0;
do_stuff(&mut val);
assert_eq!(val, 0);
多个参数守卫
use scope_guard::scope_guard;
fn do_stuff(val: &mut u32, is_run: &mut bool) {
let old_val = *val;
let mut guard = scope_guard!(|(val, is_run)| {
*val = old_val;
*is_run = false;
}, val, is_run);
*guard.0 += 1;
*guard.1 = true;
let is_ok = false; //doing some computations
if is_ok {
let (_val, _is_run) = guard.into_inner(); //analogues to forget
}
}
let mut is_run = false;
let mut val = 0;
do_stuff(&mut val, &mut is_run);
assert_eq!(val, 0);
assert!(!is_run);
let mut guard = scope_guard!(|(val, is_run)| {
*val = 1;
*is_run = true;
}, &mut val, &mut is_run);
drop(guard);
assert_eq!(val, 1);
assert!(is_run);