Skip to main content

vapoursynth4_rs/
function.rs

1use crate::{api::Api, ffi, map::Map};
2
3#[derive(Debug, PartialEq, Eq, Hash)]
4pub struct Function {
5    handle: *const ffi::VSFunction,
6    api: Api,
7}
8
9unsafe impl Send for Function {}
10
11impl Function {
12    pub(crate) unsafe fn from_ptr(ptr: *mut ffi::VSFunction, api: Api) -> Self {
13        Self { handle: ptr, api }
14    }
15
16    #[must_use]
17    pub fn as_ptr(&self) -> *mut ffi::VSFunction {
18        self.handle.cast_mut()
19    }
20
21    pub fn call(&mut self, in_: &Map, out: &mut Map) {
22        unsafe {
23            (self.api.callFunction)(self.as_ptr(), in_.as_ptr(), out.as_ptr());
24        }
25    }
26}
27
28impl Drop for Function {
29    fn drop(&mut self) {
30        unsafe { (self.api.freeFunction)(self.as_ptr()) }
31    }
32}
33
34impl Clone for Function {
35    fn clone(&self) -> Self {
36        unsafe { Self::from_ptr((self.api.addFunctionRef)(self.as_ptr()), self.api) }
37    }
38}
39
40#[cfg(all(test, feature = "link-vs"))]
41mod tests {
42    use std::{
43        ffi::c_void,
44        sync::{
45            Arc,
46            atomic::{AtomicUsize, Ordering},
47        },
48    };
49
50    use super::*;
51    use crate::{
52        core::Core,
53        key,
54        map::{AppendMode, MapMut, Value},
55    };
56
57    unsafe extern "system-unwind" fn call(
58        _: *const ffi::VSMap,
59        output: *mut ffi::VSMap,
60        data: *mut c_void,
61        _: *mut ffi::VSCore,
62        api: *const ffi::VSAPI,
63    ) {
64        unsafe {
65            let data = &*data.cast::<Arc<AtomicUsize>>();
66            data.fetch_add(1, Ordering::Relaxed);
67            let mut output = MapMut::from_ptr(output, Api::from_ptr(api));
68            let _ = output.set(key!(c"result"), Value::Int(42), AppendMode::Replace);
69        }
70    }
71
72    unsafe extern "system-unwind" fn free(data: *mut c_void) {
73        drop(unsafe { Box::from_raw(data.cast::<Arc<AtomicUsize>>()) });
74    }
75
76    #[test]
77    fn map_holds_function_reference_until_removed() -> testresult::TestResult {
78        let core = Core::builder().disable_auto_loading().build();
79        let calls = Arc::new(AtomicUsize::new(0));
80        let function = core.create_function(call, Box::new(calls.clone()), Some(free));
81        let mut map = core.create_map();
82        let key = key!(c"callback");
83        map.consume_function(key, function.clone(), AppendMode::Replace)?;
84        drop(function);
85
86        let mut stored = map.get_function(key, 0)?;
87        map.clear();
88        assert_eq!(Arc::strong_count(&calls), 2);
89        let mut output = core.create_map();
90        stored.call(&map, &mut output);
91        assert_eq!(output.get_int(key!(c"result"), 0)?, 42);
92        assert_eq!(calls.load(Ordering::Relaxed), 1);
93        drop(stored);
94        assert_eq!(Arc::strong_count(&calls), 1);
95        Ok(())
96    }
97}