neon/sys/
typedarray.rs

1use std::{ffi::c_void, mem::MaybeUninit};
2
3use super::{
4    bindings::{self as napi, TypedArrayType},
5    raw::{Env, Local},
6};
7
8#[derive(Debug)]
9/// Information describing a JavaScript [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
10pub struct TypedArrayInfo {
11    pub typ: TypedArrayType,
12    pub length: usize,
13    pub data: *mut c_void,
14    pub buf: Local,
15    pub offset: usize,
16}
17
18/// Get [information](TypedArrayInfo) describing a JavaScript `TypedArray`
19///
20/// # Safety
21/// * `env` must be valid `napi_env` for the current scope
22/// * `value` must be a handle pointing to a `TypedArray`
23pub unsafe fn info(env: Env, value: Local) -> TypedArrayInfo {
24    let mut info = MaybeUninit::<TypedArrayInfo>::zeroed();
25    let ptr = info.as_mut_ptr();
26
27    assert_eq!(
28        napi::get_typedarray_info(
29            env,
30            value,
31            &mut (*ptr).typ,
32            &mut (*ptr).length,
33            &mut (*ptr).data,
34            &mut (*ptr).buf,
35            &mut (*ptr).offset,
36        ),
37        Ok(()),
38    );
39
40    info.assume_init()
41}
42
43pub unsafe fn new(
44    env: Env,
45    typ: TypedArrayType,
46    buffer: Local,
47    offset: usize,
48    len: usize,
49) -> Result<Local, napi::Status> {
50    let mut array = MaybeUninit::uninit();
51    let status = napi::create_typedarray(env, typ, len, buffer, offset, array.as_mut_ptr());
52
53    match status {
54        Err(err @ napi::Status::PendingException) => return Err(err),
55        status => status.unwrap(),
56    };
57
58    Ok(array.assume_init())
59}