Skip to content

Commit e5f8924

Browse files
committed
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 95dc590 commit e5f8924

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
@@ -720,15 +720,19 @@ MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
720720
// Buffer, so we need to reorder on BE platforms. See
721721
// http://nodejs.org/api/buffer.html regarding Node's "ucs2"
722722
// encoding specification
723-
std::vector<uint16_t> dst;
724723
if (IsBigEndian()) {
725-
dst.assign(buf, buf + buflen);
726-
size_t nbytes = buflen * sizeof(dst[0]);
727-
SwapBytes16(reinterpret_cast<char*>(&dst[0]), nbytes);
728-
buf = &dst[0];
724+
uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen);
725+
if (dst == nullptr) {
726+
*error = SB_MALLOC_FAILED_ERROR;
727+
return MaybeLocal<Value>();
728+
}
729+
size_t nbytes = buflen * sizeof(uint16_t);
730+
memcpy(dst, buf, nbytes);
731+
SwapBytes16(reinterpret_cast<char*>(dst), nbytes);
732+
return ExternTwoByteString::New(isolate, dst, buflen, error);
733+
} else {
734+
return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
729735
}
730-
731-
return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
732736
}
733737

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

0 commit comments

Comments
 (0)