Skip to main content

jsi_rs/
array.rs

1use crate::JSRuntime;
2
3/// Wrapper around facebook::jsi::Array providing a safe Rust API
4pub struct JSArray {
5    pub(crate) inner: cxx::UniquePtr<crate::sys::ffi::JSIArray>,
6}
7
8impl JSArray {
9    /// Create a new JavaScript array with the specified length
10    pub fn new(runtime: &mut JSRuntime, length: usize) -> Self {
11        let ptr = crate::sys::ffi::create_array(runtime.pin_mut(), length);
12        Self { inner: ptr }
13    }
14
15    pub fn get(&self, runtime: &mut JSRuntime, index: usize) -> crate::JSValue {
16        if index >= self.len(runtime) {
17            return crate::JSValue::undefined();
18        }
19
20        let value =
21            crate::sys::ffi::array_get_value_at_index(runtime.pin_mut(), &self.inner, index);
22        crate::JSValue { inner: value }
23    }
24
25    pub fn set(
26        &self,
27        runtime: &mut JSRuntime,
28        index: usize,
29        value: &crate::JSValue,
30    ) -> Result<(), String> {
31        if index >= self.len(runtime) {
32            return Err(format!(
33                "Index {} out of bounds for array of length {}",
34                index,
35                self.len(runtime)
36            ));
37        }
38
39        crate::sys::ffi::array_set_value_at_index(
40            runtime.pin_mut(),
41            &self.inner,
42            index,
43            value.inner(),
44        );
45        Ok(())
46    }
47
48    pub fn len(&self, runtime: &mut JSRuntime) -> usize {
49        crate::sys::ffi::array_size(runtime.pin_mut(), &self.inner)
50    }
51
52    pub fn is_empty(&self, runtime: &mut JSRuntime) -> bool {
53        self.len(runtime) == 0
54    }
55
56    /// Access the inner UniquePtr for advanced usage
57    #[cfg(feature = "unsafe")]
58    pub fn inner(&self) -> &cxx::UniquePtr<crate::sys::ffi::JSIArray> {
59        &self.inner
60    }
61}