1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::ops::Drop;

struct ScopeExit<'a> {
    call_: Box<dyn FnMut() + 'a>,
}

impl<'a> ScopeExit<'a> {
    pub fn new<F>(call: F) -> Self
    where
        F: FnMut() + 'a,
    {
        ScopeExit {
            call_: Box::<F>::new(call),
        }
    }
}

impl<'a> Drop for ScopeExit<'a> {
    fn drop(&mut self) {
        (self.call_)()
    }
}

macro_rules! scope_exit {
    ($call: expr) => {
        let _scope_exit = ScopeExit::new($call);
    };
}

#[cfg(test)]
mod test {
    // modify local variable

    use crate::ScopeExit;
    #[test]
    fn modify_local_variable_test() {
        let mut i = 0;
        {
            let call = || {
                i = 2;
            };
            let _scope_exit = ScopeExit::new(Box::new(call));
        }
        assert_eq!(i, 2);
    }

    #[test]
    fn modify_local_variable_by_macro_test() {
        let mut i = 0;
        let mut j = 0;
        {
            scope_exit!(|| {
                i = 1;
            });

            scope_exit!(|| {
                j = 2;
            });
            // The first scope_exit also called by RAII, won't be triggered
            // by the definition of the second scope_exit.
        }
        assert_eq!(i, 1);
        assert_eq!(j, 2);
    }
}