Debian Codegraph @

third_party/rust/coremidi/src/callback.rs

raw
1 // A lifetime-managed wrapper for callback functions
2 #[derive(Debug, PartialEq)]
3 pub struct BoxedCallback<T>(*mut Box<dyn FnMut(&T)>);
4
5 impl<T> BoxedCallback<T> {
6 pub fn new<F: FnMut(&T) + Send + 'static>(f: F) -> BoxedCallback<T> {
7 BoxedCallback(Box::into_raw(Box::new(Box::new(f))))
8 }
9
10 pub fn null() -> BoxedCallback<T> {
11 BoxedCallback(::std::ptr::null_mut())
12 }
13
14 pub fn raw_ptr(&mut self) -> *mut ::std::os::raw::c_void {
15 self.0 as *mut ::std::os::raw::c_void
16 }
17
18 // must not be null
19 pub unsafe fn call_from_raw_ptr(raw_ptr: *mut ::std::os::raw::c_void, arg: &T) {
20 let callback = &mut *(raw_ptr as *mut Box<dyn FnMut(&T)>);
21 callback(arg);
22 }
23 }
24
25 unsafe impl<T> Send for BoxedCallback<T> {}
26
27 impl<T> Drop for BoxedCallback<T> {
28 fn drop(&mut self) {
29 if !self.0.is_null() {
30 unsafe {
31 let _ = Box::from_raw(self.0);
32 }
33 }
34 }
35 }