feat(napi): implement create_buffer_copy

This commit is contained in:
LongYinan 2020-10-11 21:54:23 +08:00
parent 276fc45603
commit 809ecfec49
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
4 changed files with 42 additions and 1 deletions

View file

@ -156,7 +156,7 @@ yarn test
| [napi_create_array_with_length](https://nodejs.org/api/n-api.html#n_api_napi_create_array_with_length) | 1 | v8.0.0 | ✅ |
| [napi_create_arraybuffer](https://nodejs.org/api/n-api.html#n_api_napi_create_arraybuffer) | 1 | v8.0.0 | ✅ |
| [napi_create_buffer](https://nodejs.org/api/n-api.html#n_api_napi_create_buffer) | 1 | v8.0.0 | ✅ |
| [napi_create_buffer_copy](https://nodejs.org/api/n-api.html#n_api_napi_create_buffer_copy) | 1 | v8.0.0 | ⛔️ |
| [napi_create_buffer_copy](https://nodejs.org/api/n-api.html#n_api_napi_create_buffer_copy) | 1 | v8.0.0 | |
| [napi_create_date](https://nodejs.org/api/n-api.html#n_api_napi_create_date) | 5 | v11.11.0 | ✅ |
| [napi_create_external](https://nodejs.org/api/n-api.html#n_api_napi_create_external) | 1 | v8.0.0 | ✅ |
| [napi_create_external_arraybuffer](https://nodejs.org/api/n-api.html#n_api_napi_create_external_arraybuffer) | 1 | v8.0.0 | ✅ |

View file

@ -267,6 +267,33 @@ impl Env {
))
}
pub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>
where
D: AsRef<[u8]>,
{
let length = data_to_copy.as_ref().len();
let data_ptr = data_to_copy.as_ref().as_ptr();
let mut copy_data = ptr::null_mut();
let mut raw_value = ptr::null_mut();
check_status(unsafe {
sys::napi_create_buffer_copy(
self.0,
length as u64,
data_ptr as *mut c_void,
&mut copy_data,
&mut raw_value,
)
})?;
Ok(JsBufferValue::new(
JsBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
unsafe { Vec::from_raw_parts(copy_data as *mut u8, length, length) },
))
}
pub fn create_arraybuffer(&self, length: u64) -> Result<JsArrayBufferValue> {
let mut raw_value = ptr::null_mut();
let mut data: Vec<u8> = Vec::with_capacity(length as usize);

View file

@ -11,3 +11,10 @@ test('should stringify buffer', (t) => {
const fixture = 'wow, hello'
t.is(bindings.bufferToString(Buffer.from(fixture)), fixture)
})
test('should copy', (t) => {
const fixture = Buffer.from('wow, hello')
const copyBuffer = bindings.copyBuffer(fixture)
t.deepEqual(copyBuffer, fixture)
t.not(fixture, copyBuffer)
})

View file

@ -16,8 +16,15 @@ pub fn buffer_to_string(ctx: CallContext) -> Result<JsString> {
)
}
#[js_function(1)]
pub fn copy_buffer(ctx: CallContext) -> Result<JsBuffer> {
let buffer = ctx.get::<JsBuffer>(0)?.into_value()?;
ctx.env.create_buffer_copy(buffer).map(|b| b.into_raw())
}
pub fn register_js(module: &mut Module) -> Result<()> {
module.create_named_method("getBufferLength", get_buffer_length)?;
module.create_named_method("bufferToString", buffer_to_string)?;
module.create_named_method("copyBuffer", copy_buffer)?;
Ok(())
}