优化getbuffer接口
Signed-off-by: Han <yqhanj@isoftstone.com>
This commit is contained in:
Han 2024-06-05 20:28:53 +08:00
parent 67033797d8
commit f79bd948aa
4 changed files with 31 additions and 2 deletions

View File

@ -289,6 +289,18 @@ void Buffer::ReadBytes(uint8_t *data, uint32_t offset, uint32_t length)
}
}
void Buffer::ReadBytesForArrayBuffer(void *data, uint32_t length)
{
if (length == 0) {
HILOG_DEBUG("Buffer::ReadBytesForArrayBuffer size is 0");
return;
}
if (memcpy_s(data, length, reinterpret_cast<const void*>(raw_ + byteOffset_), length) != EOK) {
HILOG_ERROR("copy raw to arraybuffer error");
return;
}
}
void Buffer::WriteByte(uint8_t number, uint32_t offset)
{
WriteBytes(&number, 1, raw_ + byteOffset_ + offset);

View File

@ -47,6 +47,7 @@ public:
void WriteUInt32LE(int32_t value, uint32_t offset);
void ReadBytes(uint8_t *data, uint32_t offset, uint32_t length);
void ReadBytesForArrayBuffer(void *data, uint32_t length);
int32_t ReadInt32BE(uint32_t offset);
int32_t ReadInt32LE(uint32_t offset);
uint32_t ReadUInt32BE(uint32_t offset);

View File

@ -610,6 +610,20 @@ static napi_value GetBufferData(napi_env env, napi_callback_info info)
return result;
}
static napi_value GetArrayBuffer(napi_env env, napi_callback_info info)
{
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr));
Buffer *buf = nullptr;
NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast<void **>(&buf)));
uint32_t length = buf->GetLength();
void *data = nullptr;
napi_value arrayBuffer = nullptr;
NAPI_CALL(env, napi_create_arraybuffer(env, length, &data, &arrayBuffer));
buf->ReadBytesForArrayBuffer(data, length);
return arrayBuffer;
}
static napi_value Get(napi_env env, napi_callback_info info)
{
napi_value thisVar = nullptr;
@ -1056,6 +1070,7 @@ static napi_value BufferInit(napi_env env, napi_value exports)
DECLARE_NAPI_FUNCTION("fillNumbers", FillNumbers),
DECLARE_NAPI_FUNCTION("fillBuffer", FillBuffer),
DECLARE_NAPI_FUNCTION("getBufferData", GetBufferData),
DECLARE_NAPI_FUNCTION("getArrayBuffer", GetArrayBuffer),
DECLARE_NAPI_FUNCTION("get", Get),
DECLARE_NAPI_FUNCTION("set", Set),
DECLARE_NAPI_FUNCTION("subBuffer", SubBuffer),

View File

@ -217,6 +217,7 @@ interface NativeBuffer {
writeUInt32LE(value: number, offset: number): number;
readUInt32LE(offset: number): number;
getBufferData(): Array<number>;
getArrayBuffer(): ArrayBufferLike;
get(index: number): number;
set(index: number, value: number): undefined;
subBuffer(target: NativeBuffer, start: number, end: number): undefined;
@ -497,8 +498,8 @@ class Buffer {
if (this._arrayBuffer) {
return this._arrayBuffer;
}
let arr = this[bufferSymbol].getBufferData();
return new Uint8Array(arr).buffer;
let arr = this[bufferSymbol].getArrayBuffer();
return arr;
}
constructor(value: number | Buffer | Uint8Array | ArrayBuffer | Array<number> | string,