Merge pull request #939 from napi-rs/fix/buffer-vec-conversion

fix(napi): impl From<Buffer> for Vec<u8>
This commit is contained in:
LongYinan 2021-12-18 13:41:40 +08:00 committed by GitHub
commit 3f2e44d3db
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 20 additions and 1 deletions

View file

@ -16,6 +16,12 @@ impl From<Vec<u8>> for Buffer {
}
}
impl From<Buffer> for Vec<u8> {
fn from(buf: Buffer) -> Self {
buf.inner.to_vec()
}
}
impl From<&[u8]> for Buffer {
fn from(inner: &[u8]) -> Self {
Buffer::from(inner.to_owned())

View file

@ -111,6 +111,7 @@ Generated by [AVA](https://avajs.dev).
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void␊
export function threadsafeFunctionFatalModeError(cb: (...args: any[]) => any): void␊
export function getBuffer(): Buffer␊
export function appendBuffer(buf: Buffer): Buffer␊
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array␊
export function mutateTypedArray(input: Float32Array): void␊

View file

@ -64,6 +64,7 @@ import {
fnReceivedAliased,
ALIAS,
AliasedStruct,
appendBuffer,
} from '../'
test('export const', (t) => {
@ -239,7 +240,10 @@ test('serde-json', (t) => {
})
test('buffer', (t) => {
t.is(getBuffer().toString('utf-8'), 'Hello world')
let buf = getBuffer()
t.is(buf.toString('utf-8'), 'Hello world')
buf = appendBuffer(buf)
t.is(buf.toString('utf-8'), 'Hello world!')
})
test('convert typedarray to vec', (t) => {

View file

@ -101,6 +101,7 @@ export function threadsafeFunctionThrowError(cb: (...args: any[]) => any): void
export function threadsafeFunctionFatalMode(cb: (...args: any[]) => any): void
export function threadsafeFunctionFatalModeError(cb: (...args: any[]) => any): void
export function getBuffer(): Buffer
export function appendBuffer(buf: Buffer): Buffer
export function convertU32Array(input: Uint32Array): Array<number>
export function createExternalTypedArray(): Uint32Array
export function mutateTypedArray(input: Float32Array): void

View file

@ -5,6 +5,13 @@ fn get_buffer() -> Buffer {
String::from("Hello world").as_bytes().into()
}
#[napi]
fn append_buffer(buf: Buffer) -> Buffer {
let mut buf = Vec::<u8>::from(buf);
buf.push('!' as u8);
buf.into()
}
#[napi]
fn convert_u32_array(input: Uint32Array) -> Vec<u32> {
input.to_vec()