fast_able/defer.rs
1/// Guard structure for defer
2/// defer 的守卫结构体
3pub struct Guard<F: FnMut()>(pub Option<F>);
4
5impl<F: FnMut()> Drop for Guard<F> {
6 fn drop(&mut self) {
7 if let Some(mut f) = (self.0).take() {
8 f()
9 }
10 }
11}
12
13/// Defers evaluation of a block of code until the end of the scope.
14/// Sort of LIFO(last-in, first-out queue)
15/// If you encounter references to resources that cannot mut more than 2 times, try nesting RefCell and then use.borrow() and.borrow_mut().
16///
17/// 延迟代码块的执行直到作用域结束。
18/// 类似于 LIFO(后进先出队列)
19/// 如果遇到不能 mut 超过 2 次的资源引用,尝试嵌套 RefCell 然后使用 .borrow() 和 .borrow_mut()。
20///
21/// for example:
22/// ```
23/// use dark_std::defer;
24/// //LIFO, so it will print: guard: 3 guard: 2 guard: 1
25/// fn main(){
26/// defer!({
27/// println!("guard: 1");
28/// });
29/// defer!(||{
30/// println!("guard: 2");
31/// });
32/// defer!{
33/// println!("guard: 3");
34/// }
35/// }
36/// ```
37///
38///
39#[macro_export]
40macro_rules! defer {
41 ($func:block) => {
42 let _guard = $crate::defer::Guard(Some( ||$func));
43 };
44 ($func:expr) => {
45 let _guard = $crate::defer::Guard(Some($func));
46 };
47 { $($func:expr$(;)?)+ } => {
48 let _guard = $crate::defer::Guard(Some( ||{$($func;)+}));
49 }
50}
51
52#[cfg(test)]
53mod test {
54 #[test]
55 fn test_defer() {
56 defer!(|| {
57 println!("defer");
58 });
59 }
60}