3 stable releases

1.2.0 Mar 11, 2023
1.1.0 Sep 9, 2022
1.0.0 Mar 3, 2021

#378 in No standard library

Download history 35/week @ 2024-07-20 5/week @ 2024-07-27 82/week @ 2024-08-03 65/week @ 2024-08-10 59/week @ 2024-08-17 67/week @ 2024-08-24 177/week @ 2024-08-31 85/week @ 2024-09-07 44/week @ 2024-09-14 97/week @ 2024-09-21 158/week @ 2024-09-28 54/week @ 2024-10-05 88/week @ 2024-10-12 77/week @ 2024-10-19 46/week @ 2024-10-26 76/week @ 2024-11-02

287 downloads per month

BSL-1.0 license

10KB
129 lines

scope-guard

Rust Crates.io Documentation

Simple RAII scope guard

Features

  • std - Enables async scope to run destructor when future finishes, even if it panics.

lib.rs:

Simple RAII scope guard

Usage:

No argument guard

use scope_guard::scope_guard;

let mut is_run = false;
{
     scope_guard!(|| {
         is_run = true;
     });
}
assert!(is_run);

Single argument guard

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);

Stacked destructor calls

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);

Multiple argument guard

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);

No runtime deps

Features