Skip to content

Commit

Permalink
perf: avoid memcpy when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Apr 3, 2022
1 parent 8dc8e48 commit 45995a3
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,28 @@ static bool IsObject (napi_env env, napi_value value) {
return type == napi_object;
}

std::string toString(napi_env& env, const napi_value& from) {
size_t size = 0;
if (IsString(env, from)) {
napi_get_value_string_utf8(env, from, NULL, 0, &size);
if (size < 4096) {
char store[4096];
napi_get_value_string_utf8(env, from, store, 4096, &size);
return std::string(store, size);
} else {
std::unique_ptr<char[]> store(new char[size + 1]);
napi_get_value_string_utf8(env, from, store.get(), size + 1, &size);
return std::string(store.get(), size);
}
} else if (IsBuffer(env, from)) {
char* data = nullptr;
napi_get_buffer_info(env, from, reinterpret_cast<void**>(&data), &size);
return std::string(data, size);
}

return "";
}

/**
* Create an error object.
*/
Expand Down Expand Up @@ -259,10 +281,7 @@ static std::optional<std::string> RangeOption (napi_env env, napi_value opts, co
napi_value value = GetProperty(env, opts, name);

if (StringOrBufferLength(env, value) >= 0) {
LD_STRING_OR_BUFFER_TO_COPY(env, value, to);
auto str = std::string(toCh_, toSz_);
delete[] toCh_;
return str;
return toString(env, value);
}
}

Expand All @@ -284,9 +303,7 @@ static std::vector<std::string>* KeyArray (napi_env env, napi_value arr) {

if (napi_get_element(env, arr, i, &element) == napi_ok &&
StringOrBufferLength(env, element) >= 0) {
LD_STRING_OR_BUFFER_TO_COPY(env, element, to);
result->emplace_back(toCh_, toSz_);
delete [] toCh_;
result->push_back(toString(env, element));
}
}
}
Expand Down

0 comments on commit 45995a3

Please sign in to comment.