Skip to content

Commit 8c0d361

Browse files
authored
napi: String API improvements (nodejs#83)
 - Make string API names consistent - Make string API coercion behavior consistent - Switch from number-remaining to number-copied results - Add UTF-16 string APIs - Add coercion APIs for number and bool - Update tests for API changes
1 parent 6e70e77 commit 8c0d361

File tree

18 files changed

+249
-243
lines changed

18 files changed

+249
-243
lines changed

src/node_api_helpers.h

+10-14
Original file line numberDiff line numberDiff line change
@@ -87,28 +87,24 @@ namespace Napi {
8787
public:
8888
inline explicit Utf8String(napi_value from) :
8989
length_(0), str_(str_st_) {
90-
if (from != NULL) {
90+
if (from != nullptr) {
9191
napi_env env;
9292
napi_get_current_env(&env);
93-
napi_value string;
93+
napi_value string = nullptr;
9494
napi_coerce_to_string(env, from, &string);
95-
if (string != NULL) {
96-
int len;
97-
napi_get_string_length(env, string, &len);
98-
size_t utf8len = 3 * len + 1;
99-
assert(utf8len <= INT_MAX);
100-
if (utf8len > sizeof(str_st_)) {
101-
str_ = new char[utf8len];
95+
if (string != nullptr) {
96+
napi_get_value_string_utf8_length(env, string, &length_);
97+
int bufsize = length_ + 1;
98+
if (static_cast<size_t>(bufsize) > sizeof(str_st_)) {
99+
str_ = new char[bufsize];
102100
assert(str_ != 0);
103101
}
104-
napi_get_string_utf8(env, string, str_,
105-
static_cast<int>(utf8len), &length_);
106-
str_[length_] = '\0';
102+
napi_get_value_string_utf8(env, string, str_, bufsize, nullptr);
107103
}
108104
}
109105
}
110106

111-
inline int length() const {
107+
inline size_t length() const {
112108
return length_;
113109
}
114110

@@ -431,7 +427,7 @@ namespace Napi {
431427
napi_get_current_env(&env);
432428

433429
napi_value s;
434-
napi_create_string(env, ErrorMessage(), &s);
430+
napi_create_string_utf8(env, ErrorMessage(), -1, &s);
435431

436432
napi_value argv[1];
437433
napi_create_error(env, s, argv);

0 commit comments

Comments
 (0)