diff --git a/src/binding.cc b/src/binding.cc index abd43ae..536336d 100644 --- a/src/binding.cc +++ b/src/binding.cc @@ -105,12 +105,12 @@ class InstanceData final : public RefNapi::Instance { auto it = pointer_to_orig_buffer.find(ptr); if (it != pointer_to_orig_buffer.end()) { + it->second.finalizer_count++; if (!it->second.ab.Value().IsEmpty()) { // Already have a valid entry, nothing to do. return; } it->second.ab.Reset(buf, 0); - it->second.finalizer_count++; } else { pointer_to_orig_buffer.emplace(ptr, ArrayBufferEntry { Reference::New(buf, 0), @@ -140,8 +140,8 @@ class InstanceData final : public RefNapi::Instance { if (it != pointer_to_orig_buffer.end()) ab = it->second.ab.Value(); - if (ab.IsEmpty()) { - length = std::max(length, kMaxLength); + if (ab.IsEmpty() || (ab.ByteLength() < length)) { + length = std::min(length, kMaxLength); ab = Buffer::New(env, ptr, length, [this](Env env, char* ptr) { UnregisterArrayBuffer(ptr); }).ArrayBuffer(); @@ -166,8 +166,15 @@ class InstanceData final : public RefNapi::Instance { */ Value WrapPointer(Env env, char* ptr, size_t length) { - if (ptr == nullptr) + if (ptr == nullptr) { length = 0; + } else if (length == 0) { + // If length is 0 N-API doesn't guarantee it will save/restore ptr normally. + // For example, see https://nodejs.org/api/n-api.html#napi_get_typedarray_info + // "[out] data: ... If the length of the array is 0, this may be NULL or any + // other pointer value." + length = 1; + } InstanceData* data; if (ptr != nullptr && (data = InstanceData::Get(env)) != nullptr) {