Skip to main content

jsi_rs/
function.rs

1use crate::sys::ffi;
2use crate::value::JSValue;
3use crate::JSRuntime;
4
5/// Wrapper around facebook::jsi::Function providing a safe Rust API
6pub struct JSFunction {
7    pub(crate) inner: cxx::UniquePtr<ffi::JSIFunction>,
8}
9
10impl JSFunction {
11    /// Call the function with the given arguments
12    pub fn call(&self, runtime: &mut JSRuntime, args: &[JSValue]) -> Result<JSValue, String> {
13        let mut vec = ffi::value_vec_create();
14        for arg in args {
15            ffi::value_vec_push(vec.pin_mut(), runtime.pin_mut(), arg.inner());
16        }
17
18        let result = ffi::function_call(runtime.pin_mut(), &self.inner, &vec);
19
20        Ok(JSValue { inner: result })
21    }
22
23    /// Call the function with explicit 'this' object
24    pub fn call_with_this(
25        &self,
26        runtime: &mut JSRuntime,
27        this_obj: &crate::JSObject,
28        args: &[JSValue],
29    ) -> Result<JSValue, String> {
30        let mut vec = ffi::value_vec_create();
31        for arg in args {
32            ffi::value_vec_push(vec.pin_mut(), runtime.pin_mut(), arg.inner());
33        }
34
35        let result = ffi::function_call_with_this(
36            runtime.pin_mut(),
37            &self.inner,
38            this_obj.inner.as_ref().expect("JSObject inner is null"),
39            &vec,
40        );
41
42        Ok(JSValue { inner: result })
43    }
44
45    /// Call the function as a constructor (using 'new')
46    pub fn call_as_constructor(
47        &self,
48        runtime: &mut JSRuntime,
49        args: &[JSValue],
50    ) -> Result<JSValue, String> {
51        let mut vec = ffi::value_vec_create();
52        for arg in args {
53            ffi::value_vec_push(vec.pin_mut(), runtime.pin_mut(), arg.inner());
54        }
55
56        let result = ffi::function_call_as_constructor(runtime.pin_mut(), &self.inner, &vec);
57
58        Ok(JSValue { inner: result })
59    }
60
61    /// Access the inner UniquePtr for advanced usage
62    #[cfg(feature = "unsafe")]
63    pub fn inner(&self) -> &cxx::UniquePtr<ffi::JSIFunction> {
64        &self.inner
65    }
66}