native buffer no need to keep raw napi pointer

This commit is contained in:
forehalo 2021-10-30 00:05:05 +08:00
parent 698bc701e8
commit 99b2723618
No known key found for this signature in database
GPG key ID: 64382C5AF49F3EB9
5 changed files with 23 additions and 38 deletions

View file

@ -5,14 +5,12 @@ use crate::{bindgen_prelude::*, check_status, sys, Result, ValueType};
/// zero copy u8 vector shared between rust and napi /// zero copy u8 vector shared between rust and napi
pub struct Buffer { pub struct Buffer {
raw: Option<sys::napi_value>,
inner: mem::ManuallyDrop<Vec<u8>>, inner: mem::ManuallyDrop<Vec<u8>>,
} }
impl From<Vec<u8>> for Buffer { impl From<Vec<u8>> for Buffer {
fn from(data: Vec<u8>) -> Self { fn from(data: Vec<u8>) -> Self {
Buffer { Buffer {
raw: None,
inner: mem::ManuallyDrop::new(data), inner: mem::ManuallyDrop::new(data),
} }
} }
@ -67,7 +65,6 @@ impl FromNapiValue for Buffer {
)?; )?;
Ok(Self { Ok(Self {
raw: Some(napi_val),
inner: mem::ManuallyDrop::new(Vec::from_raw_parts(buf as *mut _, len, len)), inner: mem::ManuallyDrop::new(Vec::from_raw_parts(buf as *mut _, len, len)),
}) })
} }
@ -75,26 +72,21 @@ impl FromNapiValue for Buffer {
impl ToNapiValue for Buffer { impl ToNapiValue for Buffer {
unsafe fn to_napi_value(env: sys::napi_env, mut val: Self) -> Result<sys::napi_value> { unsafe fn to_napi_value(env: sys::napi_env, mut val: Self) -> Result<sys::napi_value> {
match val.raw { let len = val.inner.len();
Some(raw) => Ok(raw), let mut ret = ptr::null_mut();
None => { check_status!(
let len = val.inner.len(); sys::napi_create_external_buffer(
let mut ret = ptr::null_mut(); env,
check_status!( len,
sys::napi_create_external_buffer( val.inner.as_mut_ptr() as *mut _,
env, Some(drop_buffer),
len, Box::into_raw(Box::new((len, val.inner.capacity()))) as *mut _,
val.inner.as_mut_ptr() as *mut _, &mut ret,
Some(drop_buffer), ),
Box::into_raw(Box::new((len, val.inner.capacity()))) as *mut _, "Failed to create napi buffer"
&mut ret, )?;
),
"Failed to create napi buffer"
)?;
Ok(ret) Ok(ret)
}
}
} }
} }
@ -103,9 +95,3 @@ impl ValidateNapiValue for Buffer {
vec![ValueType::Object] vec![ValueType::Object]
} }
} }
impl ToNapiValue for Vec<u8> {
unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result<sys::napi_value> {
Buffer::to_napi_value(env, val.into())
}
}

View file

@ -11,7 +11,7 @@ Generated by [AVA](https://avajs.dev).
`export function getWords(): Array<string> `export function getWords(): Array<string>
export function getNums(): Array<number> export function getNums(): Array<number>
export function sumNums(nums: Array<number>): number␊ export function sumNums(nums: Array<number>): number␊
export function readFileAsync(path: string): Promise<Array<number>> export function readFileAsync(path: string): Promise<Buffer>
export function getCwd(callback: (arg0: string) => void): void␊ export function getCwd(callback: (arg0: string) => void): void␊
export function readFile(callback: (arg0: Error | undefined, arg1: string | null) => void): void␊ export function readFile(callback: (arg0: Error | undefined, arg1: string | null) => void): void␊
export enum Kind { Dog = 0, Cat = 1, Duck = 2 }␊ export enum Kind { Dog = 0, Cat = 1, Duck = 2 }␊

View file

@ -1,7 +1,7 @@
export function getWords(): Array<string> export function getWords(): Array<string>
export function getNums(): Array<number> export function getNums(): Array<number>
export function sumNums(nums: Array<number>): number export function sumNums(nums: Array<number>): number
export function readFileAsync(path: string): Promise<Array<number>> export function readFileAsync(path: string): Promise<Buffer>
export function getCwd(callback: (arg0: string) => void): void export function getCwd(callback: (arg0: string) => void): void
export function readFile(callback: (arg0: Error | undefined, arg1: string | null) => void): void export function readFile(callback: (arg0: Error | undefined, arg1: string | null) => void): void
export enum Kind { Dog = 0, Cat = 1, Duck = 2 } export enum Kind { Dog = 0, Cat = 1, Duck = 2 }

View file

@ -3,15 +3,14 @@ use napi::bindgen_prelude::*;
use tokio::fs; use tokio::fs;
#[napi] #[napi]
async fn read_file_async(path: String) -> Result<Vec<u8>> { async fn read_file_async(path: String) -> Result<Buffer> {
fs::read(path) fs::read(path)
.map(|v| { .map(|r| match r {
v.map_err(|e| { Ok(content) => Ok(content.into()),
Error::new( Err(e) => Err(Error::new(
Status::GenericFailure, Status::GenericFailure,
format!("failed to read file, {}", e), format!("failed to read file, {}", e),
) )),
})
}) })
.await .await
} }