Skip to content

Commit

Permalink
src: simplify node::Utf8Value()
Browse files Browse the repository at this point in the history
* Remove kStorageSize constant.

* Remove superfluous local variable and reinterpret_cast.

* Reorder data members so the length field and data pointer
  (if not the data itself) fit in a single cache line.

PR-URL: #1042
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
  • Loading branch information
bnoordhuis committed Mar 5, 2015
1 parent 364cc7e commit c9ee654
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
21 changes: 8 additions & 13 deletions src/util.cc
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#include "util.h"

#include "string_bytes.h"

namespace node {

Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value)
: length_(0), str_(nullptr) {
: length_(0), str_(str_st_) {
if (value.IsEmpty())
return;

Expand All @@ -15,19 +14,15 @@ Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value)

// Allocate enough space to include the null terminator
size_t len = StringBytes::StorageSize(val_, UTF8) + 1;

char* str;
if (len > kStorageSize)
str = static_cast<char*>(malloc(len));
else
str = str_st_;
CHECK_NE(str, NULL);
if (len > sizeof(str_st_)) {
str_ = static_cast<char*>(malloc(len));
CHECK_NE(str_, nullptr);
}

const int flags =
v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;
length_ = val_->WriteUtf8(str, len, 0, flags);
str[length_] = '\0';

str_ = reinterpret_cast<char*>(str);
length_ = val_->WriteUtf8(str_, len, 0, flags);
str_[length_] = '\0';
}

} // namespace node
3 changes: 1 addition & 2 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,9 @@ class Utf8Value {
};

private:
static const int kStorageSize = 1024;
size_t length_;
char str_st_[kStorageSize];
char* str_;
char str_st_[1024];
};

} // namespace node
Expand Down

0 comments on commit c9ee654

Please sign in to comment.