Skip to content

Commit 45995a3

Browse files
committed
perf: avoid memcpy when possible
1 parent 8dc8e48 commit 45995a3

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

binding.cc

+24-7
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,28 @@ static bool IsObject (napi_env env, napi_value value) {
9595
return type == napi_object;
9696
}
9797

98+
std::string toString(napi_env& env, const napi_value& from) {
99+
size_t size = 0;
100+
if (IsString(env, from)) {
101+
napi_get_value_string_utf8(env, from, NULL, 0, &size);
102+
if (size < 4096) {
103+
char store[4096];
104+
napi_get_value_string_utf8(env, from, store, 4096, &size);
105+
return std::string(store, size);
106+
} else {
107+
std::unique_ptr<char[]> store(new char[size + 1]);
108+
napi_get_value_string_utf8(env, from, store.get(), size + 1, &size);
109+
return std::string(store.get(), size);
110+
}
111+
} else if (IsBuffer(env, from)) {
112+
char* data = nullptr;
113+
napi_get_buffer_info(env, from, reinterpret_cast<void**>(&data), &size);
114+
return std::string(data, size);
115+
}
116+
117+
return "";
118+
}
119+
98120
/**
99121
* Create an error object.
100122
*/
@@ -259,10 +281,7 @@ static std::optional<std::string> RangeOption (napi_env env, napi_value opts, co
259281
napi_value value = GetProperty(env, opts, name);
260282

261283
if (StringOrBufferLength(env, value) >= 0) {
262-
LD_STRING_OR_BUFFER_TO_COPY(env, value, to);
263-
auto str = std::string(toCh_, toSz_);
264-
delete[] toCh_;
265-
return str;
284+
return toString(env, value);
266285
}
267286
}
268287

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

285304
if (napi_get_element(env, arr, i, &element) == napi_ok &&
286305
StringOrBufferLength(env, element) >= 0) {
287-
LD_STRING_OR_BUFFER_TO_COPY(env, element, to);
288-
result->emplace_back(toCh_, toSz_);
289-
delete [] toCh_;
306+
result->push_back(toString(env, element));
290307
}
291308
}
292309
}

0 commit comments

Comments
 (0)