Skip to content

Commit

Permalink
fix(napi): fallback to copy buffer if zero copy is not allowed (#1445)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Jan 19, 2023
1 parent bdbdbcc commit fda0aa0
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 166 deletions.
21 changes: 18 additions & 3 deletions crates/napi/src/bindgen_runtime/js_values/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,16 +231,31 @@ impl ToNapiValue for Buffer {
// the same data pointer if it's 0x0.
unsafe { sys::napi_create_buffer(env, len, ptr::null_mut(), &mut ret) }
} else {
unsafe {
let value_ptr = val.inner.as_ptr();
let val_box_ptr = Box::into_raw(Box::new(val));
let mut status = unsafe {
sys::napi_create_external_buffer(
env,
len,
val.inner.as_ptr() as *mut c_void,
value_ptr as *mut c_void,
Some(drop_buffer),
Box::into_raw(Box::new(val)) as *mut c_void,
val_box_ptr as *mut c_void,
&mut ret,
)
};
if status == napi_sys::Status::napi_no_external_buffers_allowed {
let value = unsafe { Box::from_raw(val_box_ptr) };
status = unsafe {
sys::napi_create_buffer_copy(
env,
len,
value.inner.as_ptr() as *mut c_void,
ptr::null_mut(),
&mut ret,
)
};
}
status
},
"Failed to create napi buffer"
)?;
Expand Down
1 change: 1 addition & 0 deletions crates/sys/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ pub mod Status {
pub const napi_arraybuffer_expected: i32 = 19;
pub const napi_detachable_arraybuffer_expected: i32 = 20;
pub const napi_would_deadlock: i32 = 21; // unused
pub const napi_no_external_buffers_allowed: i32 = 22;
}

pub type napi_callback =
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
"c8": "^7.12.0",
"colorette": "^2.0.19",
"cross-env": "^7.0.3",
"electron": "20.3.3",
"electron": "22.0.3",
"esbuild": "^0.17.2",
"eslint": "^8.32.0",
"eslint-config-prettier": "^8.6.0",
Expand Down

0 comments on commit fda0aa0

Please sign in to comment.