feat(napi): AsMut and DerefMut for JsBuffer
This commit is contained in:
parent
ff66f102de
commit
501313789d
4 changed files with 35 additions and 3 deletions
|
@ -1,5 +1,5 @@
|
|||
use std::mem;
|
||||
use std::ops::Deref;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::os::raw::c_void;
|
||||
use std::ptr;
|
||||
|
||||
|
@ -196,6 +196,12 @@ impl Deref for JsArrayBufferValue {
|
|||
}
|
||||
}
|
||||
|
||||
impl DerefMut for JsArrayBufferValue {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.data.as_mut_slice()
|
||||
}
|
||||
}
|
||||
|
||||
impl JsTypedArray {
|
||||
/// get TypeArray info
|
||||
/// https://nodejs.org/api/n-api.html#n_api_napi_get_typedarray_info
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use std::mem;
|
||||
use std::ops::Deref;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::ptr;
|
||||
|
||||
use super::Value;
|
||||
|
@ -76,6 +76,12 @@ impl AsRef<[u8]> for JsBufferValue {
|
|||
}
|
||||
}
|
||||
|
||||
impl AsMut<[u8]> for JsBufferValue {
|
||||
fn as_mut(&mut self) -> &mut [u8] {
|
||||
self.data.as_mut_slice()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for JsBufferValue {
|
||||
type Target = [u8];
|
||||
|
||||
|
@ -83,3 +89,9 @@ impl Deref for JsBufferValue {
|
|||
self.data.as_slice()
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for JsBufferValue {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.data.as_mut_slice()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -32,3 +32,9 @@ test('should create borrowed buffer with finalize', (t) => {
|
|||
Buffer.from([1, 2, 3]),
|
||||
)
|
||||
})
|
||||
|
||||
test('should be able to mutate buffer', (t) => {
|
||||
const fixture = Buffer.from([0, 1])
|
||||
bindings.mutateBuffer(fixture)
|
||||
t.is(fixture[1], 42)
|
||||
})
|
||||
|
|
|
@ -3,7 +3,7 @@ use std::str;
|
|||
|
||||
use napi::{
|
||||
noop_finalize, CallContext, ContextlessResult, Env, Error, JsBuffer, JsNumber, JsObject,
|
||||
JsString, Result, Status,
|
||||
JsString, JsUndefined, Result, Status,
|
||||
};
|
||||
|
||||
#[js_function(1)]
|
||||
|
@ -57,6 +57,13 @@ pub fn create_borrowed_buffer_with_finalize(env: Env) -> ContextlessResult<JsBuf
|
|||
.map(|b| Some(b.into_raw()))
|
||||
}
|
||||
|
||||
#[js_function(1)]
|
||||
fn mutate_buffer(ctx: CallContext) -> Result<JsUndefined> {
|
||||
let buffer = &mut ctx.get::<JsBuffer>(0)?.into_value()?;
|
||||
buffer[1] = 42;
|
||||
ctx.env.get_undefined()
|
||||
}
|
||||
|
||||
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
||||
exports.create_named_method("getBufferLength", get_buffer_length)?;
|
||||
exports.create_named_method("bufferToString", buffer_to_string)?;
|
||||
|
@ -69,5 +76,6 @@ pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
|||
"createBorrowedBufferWithFinalize",
|
||||
create_borrowed_buffer_with_finalize,
|
||||
)?;
|
||||
exports.create_named_method("mutateBuffer", mutate_buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue