diff --git a/napi/src/js_values/arraybuffer.rs b/napi/src/js_values/arraybuffer.rs index 45b961c1..e0c89f70 100644 --- a/napi/src/js_values/arraybuffer.rs +++ b/napi/src/js_values/arraybuffer.rs @@ -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 diff --git a/napi/src/js_values/buffer.rs b/napi/src/js_values/buffer.rs index b3926259..a57c3b33 100644 --- a/napi/src/js_values/buffer.rs +++ b/napi/src/js_values/buffer.rs @@ -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() + } +} diff --git a/test_module/__test__/buffer.spec.ts b/test_module/__test__/buffer.spec.ts index 5f5d4865..b41faee6 100644 --- a/test_module/__test__/buffer.spec.ts +++ b/test_module/__test__/buffer.spec.ts @@ -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) +}) diff --git a/test_module/src/buffer.rs b/test_module/src/buffer.rs index 622dabab..45628d07 100644 --- a/test_module/src/buffer.rs +++ b/test_module/src/buffer.rs @@ -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 Result { + let buffer = &mut ctx.get::(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(()) }