diff --git a/src/node.h b/src/node.h index 80bb20d40a693a..d31bd6d72219da 100644 --- a/src/node.h +++ b/src/node.h @@ -274,6 +274,7 @@ NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, size_t len, enum encoding encoding = BINARY); +// The input buffer should be in host endianness. NODE_EXTERN v8::Local Encode(v8::Isolate* isolate, const uint16_t* buf, size_t len); diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 17477c01fa4f78..420dc293af5684 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -276,7 +276,11 @@ void StringSlice(const FunctionCallbackInfo& args) { const uint16_t* buf; bool release = false; - if (reinterpret_cast(data) % sizeof(*buf) == 0) { + // Node's "ucs2" encoding expects LE character data inside a Buffer, so we + // need to reorder on BE platforms. See http://nodejs.org/api/buffer.html + // regarding Node's "ucs2" encoding specification. + const bool aligned = (reinterpret_cast(data) % sizeof(*buf) == 0); + if (IsLittleEndian() && aligned) { buf = reinterpret_cast(data); } else { // Make a copy to avoid unaligned accesses in v8::String::NewFromTwoByte(). diff --git a/src/string_bytes.cc b/src/string_bytes.cc index e646087b9ddd6e..f1ff697452f58c 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -777,19 +777,6 @@ Local StringBytes::Encode(Isolate* isolate, size_t buflen) { const uint16_t* src = buf; - // Node's "ucs2" encoding expects LE character data inside a - // Buffer, so we need to reorder on BE platforms. See - // http://nodejs.org/api/buffer.html regarding Node's "ucs2" - // encoding specification. - if (IsBigEndian()) { - // Inefficient, see StringSlice() in src/node_buffer.cc; - // this is potentially the second copy of the actual input. - uint16_t* copy = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i += 1) - copy[i] = buf[i] << 8 | buf[i] >> 8; - src = copy; - } - Local val; if (buflen < EXTERN_APEX) { val = String::NewFromTwoByte(isolate, diff --git a/src/string_bytes.h b/src/string_bytes.h index a67bd45e49f4e4..1f798752883d00 100644 --- a/src/string_bytes.h +++ b/src/string_bytes.h @@ -77,6 +77,7 @@ class StringBytes { size_t buflen, enum encoding encoding); + // The input buffer should be in host endianness. static v8::Local Encode(v8::Isolate* isolate, const uint16_t* buf, size_t buflen);