Merge pull request #1066 from napi-rs/issue/deref-u8-array

fix(napi): deref from Uint8ClampedArray
This commit is contained in:
LongYinan 2022-02-07 14:40:41 +08:00 committed by GitHub
commit 102b29c777
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 17 additions and 1 deletions

View file

@ -263,7 +263,8 @@ impl JsTypedArray {
impl JsTypedArrayValue {
#[inline]
fn is_valid_as_ref(&self, dest_type: TypedArrayType) {
if self.typedarray_type == TypedArrayType::Uint8Clamped && dest_type != TypedArrayType::Uint8 {
// deref `Uint8ClampedArray` as `&[u8]` is valid
if self.typedarray_type == TypedArrayType::Uint8Clamped && dest_type == TypedArrayType::Uint8 {
return;
}
if self.typedarray_type != dest_type {

View file

@ -145,6 +145,7 @@ Generated by [AVA](https://avajs.dev).
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array␊
export function mutateTypedArray(input: Float32Array): void␊
export function derefUint8Array(a: Uint8Array, b: Uint8ClampedArray): number␊
/**␊
* \`constructor\` option for \`struct\` requires all fields to be public,␊
* otherwise tag impl fn as constructor␊

View file

@ -83,6 +83,7 @@ import {
testSerdeRoundtrip,
createObjWithProperty,
dateToNumber,
derefUint8Array,
} from '../'
test('export const', (t) => {
@ -358,6 +359,13 @@ test('mutate TypedArray', (t) => {
t.deepEqual(input, new Float32Array([2.0, 4.0, 6.0, 8.0, 10.0]))
})
test('deref uint8 array', (t) => {
t.is(
derefUint8Array(new Uint8Array([1, 2]), new Uint8ClampedArray([3, 4])),
4,
)
})
test('async', async (t) => {
const bufPromise = readFileAsync(join(__dirname, '../package.json'))
await t.notThrowsAsync(bufPromise)

View file

@ -135,6 +135,7 @@ export function appendBuffer(buf: Buffer): Buffer
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array
export function mutateTypedArray(input: Float32Array): void
export function derefUint8Array(a: Uint8Array, b: Uint8ClampedArray): number
/**
* `constructor` option for `struct` requires all fields to be public,
* otherwise tag impl fn as constructor

View file

@ -28,3 +28,8 @@ fn mutate_typed_array(mut input: Float32Array) {
*item *= 2.0;
}
}
#[napi]
fn deref_uint8_array(a: Uint8Array, b: Uint8ClampedArray) -> u32 {
(a.len() + b.len()) as u32
}