vertigo/computed/
drop_resource.rs

1use std::any::Any;
2
3/// A struct used by [driver](struct.Driver.html) to tidy things up on javascript side after a rust object goes out of scope.
4pub enum DropResource {
5    Fun(Option<Box<dyn FnOnce()>>),
6    Struct(Box<dyn Any>),
7}
8
9impl DropResource {
10    pub fn new<F: FnOnce() + 'static>(drop_fun: F) -> DropResource {
11        DropResource::Fun(Some(Box::new(drop_fun)))
12    }
13
14    pub fn from_struct(inst: impl Any) -> DropResource {
15        DropResource::Struct(Box::new(inst))
16    }
17
18    pub fn off(self) {}
19}
20
21impl Drop for DropResource {
22    fn drop(&mut self) {
23        match self {
24            Self::Fun(inner) => {
25                let drop_fun = std::mem::take(inner);
26
27                if let Some(drop_fun) = drop_fun {
28                    drop_fun();
29                }
30            }
31            Self::Struct(_) => {}
32        }
33    }
34}