1 use crate::TreeBuilder;
2 
3 /// A deferred function called with an argument, `TreeBuilder`
4 pub struct DeferredFn<F: Fn(TreeBuilder) -> ()> {
5     tree: Option<TreeBuilder>,
6     action: Option<F>,
7 }
8 
9 impl<F> DeferredFn<F>
10 where
11     F: Fn(TreeBuilder) -> (),
12 {
13     /// Create a new deferred function based on `tree`
new(tree: TreeBuilder, action: F) -> Self14     pub fn new(tree: TreeBuilder, action: F) -> Self {
15         DeferredFn {
16             tree: Some(tree),
17             action: Some(action),
18         }
19     }
20     /// Create an empty deferred function
21     /// This does nothing when scope ends
none() -> Self22     pub fn none() -> Self {
23         DeferredFn {
24             tree: None,
25             action: None,
26         }
27     }
28 
29     /// Disables the deferred function
30     /// This prevents the function from executing when the scope ends
cancel(&mut self)31     pub fn cancel(&mut self) {
32         self.tree = None;
33         self.action = None;
34     }
35 }
36 
37 impl<F> Drop for DeferredFn<F>
38 where
39     F: Fn(TreeBuilder) -> (),
40 {
drop(&mut self)41     fn drop(&mut self) {
42         if let (Some(x), Some(action)) = (&self.tree, &self.action) {
43             action(x.clone());
44         }
45     }
46 }
47