Browse Source

src: move BE/LE buffer conversion to StringSlice()

Move the big endian to little endian conversion logic for UCS2 input
from src/string_bytes.cc to src/node_buffer.cc; StringSlice() is the
only function that actually needs it and with this commit, a second
copy is avoided on big endian architectures.
archived-io.js-v0.12
Ben Noordhuis 10 years ago
parent
commit
52fc406308
  1. 1
      src/node.h
  2. 6
      src/node_buffer.cc
  3. 13
      src/string_bytes.cc
  4. 1
      src/string_bytes.h

1
src/node.h

@ -274,6 +274,7 @@ NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
size_t len,
enum encoding encoding = BINARY);
// The input buffer should be in host endianness.
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
const uint16_t* buf,
size_t len);

6
src/node_buffer.cc

@ -276,7 +276,11 @@ void StringSlice<UCS2>(const FunctionCallbackInfo<Value>& args) {
const uint16_t* buf;
bool release = false;
if (reinterpret_cast<uintptr_t>(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<uintptr_t>(data) % sizeof(*buf) == 0);
if (IsLittleEndian() && aligned) {
buf = reinterpret_cast<const uint16_t*>(data);
} else {
// Make a copy to avoid unaligned accesses in v8::String::NewFromTwoByte().

13
src/string_bytes.cc

@ -777,19 +777,6 @@ Local<Value> 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<UCS2>() 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<String> val;
if (buflen < EXTERN_APEX) {
val = String::NewFromTwoByte(isolate,

1
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<v8::Value> Encode(v8::Isolate* isolate,
const uint16_t* buf,
size_t buflen);

Loading…
Cancel
Save