Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Heap allocated jsstring char* conversion
  • Loading branch information
petkaantonov committed Feb 13, 2016
commit 3b54e708ff84996857c7907f0b2d4cc23d03c05e
19 changes: 19 additions & 0 deletions src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@

namespace node {

char* ToUtf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value) {
if (value.IsEmpty())
return nullptr;

v8::Local<v8::String> string_value = value->ToString(isolate);
if (string_value.IsEmpty())
return nullptr;

// Allocate enough space to include the null terminator
size_t len = StringBytes::StorageSize(isolate, string_value, UTF8) + 1;
char* res = static_cast<char*>(malloc(len));

const int flags =
v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;
int length = string_value->WriteUtf8(res, len, 0, flags);
res[length] = '\0';
return res;
}

Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value)
: length_(0), str_(str_st_) {
if (value.IsEmpty())
Expand Down
2 changes: 2 additions & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ inline TypeName* Unwrap(v8::Local<v8::Object> object);

inline void SwapBytes(uint16_t* dst, const uint16_t* src, size_t buflen);

char* ToUtf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value);

class Utf8Value {
public:
explicit Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> value);
Expand Down