feat(napi): support TypedArray input and output

This commit is contained in:
LongYinan 2021-11-30 18:43:34 +08:00
parent fa23769e9d
commit d9c53d728b
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
22 changed files with 510 additions and 227 deletions

View file

@ -96,6 +96,9 @@ Generated by [AVA](https://avajs.dev).
export function threadsafeFunctionThrowError(cb: (...args: any[]) => any): void␊
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void␊
export function getBuffer(): Buffer␊
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array␊
export function mutateTypedArray(input: Float32Array): void␊
/**␊
* \`constructor\` option for \`struct\` requires all fields to be public,␊
* otherwise tag impl fn as constructor␊

View file

@ -56,6 +56,9 @@ import {
xxh3,
xxh64Alias,
tsRename,
convertU32Array,
createExternalTypedArray,
mutateTypedArray,
} from '../'
test('export const', (t) => {
@ -213,6 +216,21 @@ test('buffer', (t) => {
t.is(getBuffer().toString('utf-8'), 'Hello world')
})
test('convert typedarray to vec', (t) => {
const input = new Uint32Array([1, 2, 3, 4, 5])
t.deepEqual(convertU32Array(input), Array.from(input))
})
test('create external TypedArray', (t) => {
t.deepEqual(createExternalTypedArray(), new Uint32Array([1, 2, 3, 4, 5]))
})
test('mutate TypedArray', (t) => {
const input = new Float32Array([1, 2, 3, 4, 5])
mutateTypedArray(input)
t.deepEqual(input, new Float32Array([2.0, 4.0, 6.0, 8.0, 10.0]))
})
test('async', async (t) => {
const bufPromise = readFileAsync(join(__dirname, '../package.json'))
await t.notThrowsAsync(bufPromise)

View file

@ -23,6 +23,7 @@ Generated by [AVA](https://avajs.dev).
'ava',
'benny',
'c8',
'chalk',
'cross-env',
'esbuild',
'eslint',

View file

@ -86,6 +86,9 @@ export function callThreadsafeFunction(callback: (...args: any[]) => any): void
export function threadsafeFunctionThrowError(cb: (...args: any[]) => any): void
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void
export function getBuffer(): Buffer
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array
export function mutateTypedArray(input: Float32Array): void
/**
* `constructor` option for `struct` requires all fields to be public,
* otherwise tag impl fn as constructor

View file

@ -4,3 +4,20 @@ use napi::bindgen_prelude::*;
fn get_buffer() -> Buffer {
String::from("Hello world").as_bytes().into()
}
#[napi]
fn convert_u32_array(input: Uint32Array) -> Vec<u32> {
input.to_vec()
}
#[napi]
fn create_external_typed_array() -> Uint32Array {
Uint32Array::new(vec![1, 2, 3, 4, 5])
}
#[napi]
fn mutate_typed_array(mut input: Float32Array) {
for item in input.as_mut() {
*item *= 2.0;
}
}