From 5fc62fe2a16825f22e3fab542cc88dcadcb607b7 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 4 Apr 2018 21:23:34 +0800 Subject: [PATCH] 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. --- src/string_bytes.cc | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 2b485746dff5df..624eb92b930c12 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -720,15 +720,19 @@ MaybeLocal StringBytes::Encode(Isolate* isolate, // Buffer, so we need to reorder on BE platforms. See // http://nodejs.org/api/buffer.html regarding Node's "ucs2" // encoding specification - std::vector dst; if (IsBigEndian()) { - dst.assign(buf, buf + buflen); - size_t nbytes = buflen * sizeof(dst[0]); - SwapBytes16(reinterpret_cast(&dst[0]), nbytes); - buf = &dst[0]; + uint16_t* dst = node::UncheckedMalloc(buflen); + if (dst == nullptr) { + *error = SB_MALLOC_FAILED_ERROR; + return MaybeLocal(); + } + size_t nbytes = buflen * sizeof(uint16_t); + memcpy(dst, buf, nbytes); + SwapBytes16(reinterpret_cast(dst), nbytes); + return ExternTwoByteString::New(isolate, dst, buflen, error); + } else { + return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error); } - - return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error); } MaybeLocal StringBytes::Encode(Isolate* isolate,