Skip to content

Commit 2209b81

Browse files
joyeecheungtargos
authored andcommitted
buffer: reduce overhead of StringBytes::Encode for UCS2
Currently calling StringBytes::Encode on a UCS2 buffer results in two copies of the buffer and the usage of std::vector::assign makes the memory usage unpredictable, and therefore hard to test against. This patch makes the memory usage more predictable by allocating the memory using node::UncheckedMalloc and handles the memory allocation failure properly. Only one copy of the buffer will be created and it will be freed upon GC of the string. PR-URL: #19798 Refs: #19739 Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent ee63bfa commit 2209b81

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/string_bytes.cc

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -775,15 +775,19 @@ MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
775775
// Buffer, so we need to reorder on BE platforms. See
776776
// http://nodejs.org/api/buffer.html regarding Node's "ucs2"
777777
// encoding specification
778-
std::vector<uint16_t> dst;
779778
if (IsBigEndian()) {
780-
dst.assign(buf, buf + buflen);
781-
size_t nbytes = buflen * sizeof(dst[0]);
782-
SwapBytes16(reinterpret_cast<char*>(&dst[0]), nbytes);
783-
buf = &dst[0];
779+
uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen);
780+
if (dst == nullptr) {
781+
*error = SB_MALLOC_FAILED_ERROR;
782+
return MaybeLocal<Value>();
783+
}
784+
size_t nbytes = buflen * sizeof(uint16_t);
785+
memcpy(dst, buf, nbytes);
786+
SwapBytes16(reinterpret_cast<char*>(dst), nbytes);
787+
return ExternTwoByteString::New(isolate, dst, buflen, error);
788+
} else {
789+
return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
784790
}
785-
786-
return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
787791
}
788792

789793
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,

0 commit comments

Comments
 (0)