nodex_api/value/
array.rs

1use crate::{api, prelude::*};
2use std::{mem::MaybeUninit, os::raw::c_char};
3
4#[derive(Copy, Clone, Debug)]
5pub struct JsArray(pub(crate) JsValue);
6
7impl JsArray {
8    pub(crate) fn from_value(value: JsValue) -> JsArray {
9        JsArray(value)
10    }
11
12    /// This API returns a Node-API value corresponding to a JavaScript Array type. The Array's
13    /// length property is set to the passed-in length parameter. However, the underlying buffer
14    /// is not guaranteed to be pre-allocated by the VM when the array is created. That behavior
15    /// is left to the underlying VM implementation. If the buffer must be a contiguous block of
16    /// memory that can be directly read and/or written via C, consider using napi_create_external_arraybuffer.
17    ///
18    /// JavaScript arrays are described in Section 22.1 of the ECMAScript Language Specification.
19    pub fn new(env: NapiEnv, length: usize) -> NapiResult<JsArray> {
20        let value = napi_call!(=napi_create_array_with_length, env, length);
21        Ok(JsArray(JsValue::from_raw(env, value)))
22    }
23
24    /// This API returns a Node-API value corresponding to a JavaScript Array type. JavaScript
25    /// arrays are described in Section 22.1 of the ECMAScript Language Specification.
26    pub fn empty(env: NapiEnv) -> NapiResult<JsArray> {
27        let value = napi_call!(=napi_create_array, env);
28        Ok(JsArray(JsValue::from_raw(env, value)))
29    }
30
31    /// This API returns the length of an array.
32    /// Array length is described in Section 22.1.4.1 of the ECMAScript Language Specification.
33    pub fn len(&self) -> NapiResult<u32> {
34        Ok(napi_call!(=napi_get_array_length, self.env(), self.raw()))
35    }
36
37    /// This array is empty.
38    pub fn is_empty(&self) -> NapiResult<bool> {
39        Ok(self.len()? == 0)
40    }
41
42    /// Get element at `index`
43    #[inline]
44    pub fn get(&self, index: u32) -> NapiResult<JsValue> {
45        Ok(JsValue::from_raw(
46            self.env(),
47            napi_call!(=napi_get_element, self.env(), self.raw(), index),
48        ))
49    }
50
51    /// Set element at `index`
52    #[inline]
53    pub fn set(&mut self, index: u32, value: impl NapiValueT) -> NapiResult<()> {
54        napi_call!(napi_set_element, self.env(), self.raw(), index, value.raw())
55    }
56}
57
58napi_value_t!(JsArray);
59
60impl NapiValueCheck for JsArray {
61    /// This API represents invoking the IsArray operation on the object as defined in Section
62    /// 7.2.2 of the ECMAScript Language Specification.
63    fn check(&self) -> NapiResult<bool> {
64        Ok(napi_call!(=napi_is_array, self.env(), self.raw()))
65    }
66}