Skip to content

Commit

Permalink
Fixed Array.length setter.
Browse files Browse the repository at this point in the history
This closes #26 and closes #27 issues on Github.
  • Loading branch information
drsm committed Jul 26, 2019
1 parent 7bed35a commit 0b4030f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
21 changes: 14 additions & 7 deletions njs/njs_array.c
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,11 @@ njs_array_length(njs_vm_t *vm, njs_value_t *value, njs_value_t *setval,
njs_value_t *val;
njs_array_t *array;
njs_object_t *proto;
njs_value_t val_length;

proto = njs_object(value);

if (setval == NULL) {
if (nxt_fast_path(setval == NULL)) {
do {
if (nxt_fast_path(proto->type == NJS_ARRAY)) {
break;
Expand All @@ -345,13 +346,19 @@ njs_array_length(njs_vm_t *vm, njs_value_t *value, njs_value_t *setval,
return NJS_DECLINED;
}

if (!njs_is_number(setval)) {
njs_range_error(vm, "Invalid array length");
return NJS_ERROR;
if (nxt_slow_path(!njs_is_number(setval))) {
ret = njs_value_to_numeric(vm, &val_length, setval);
if (ret != NXT_OK) {
return ret;
}

num = njs_number(&val_length);

} else {
num = njs_number(setval);
}

num = njs_number(setval);
length = (uint32_t) num;
length = njs_number_to_uint32(num);

if ((double) length != num) {
njs_range_error(vm, "Invalid array length");
Expand Down Expand Up @@ -379,7 +386,7 @@ njs_array_length(njs_vm_t *vm, njs_value_t *value, njs_value_t *setval,

array->length = length;

njs_set_number(retval, length);
*retval = *setval;
return NJS_OK;
}

Expand Down
20 changes: 20 additions & 0 deletions njs/test/njs_unit_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -3531,6 +3531,26 @@ static njs_unit_test_t njs_test[] =
{ nxt_string("[].length = -1"),
nxt_string("RangeError: Invalid array length") },

{ nxt_string("var a = [1];"
"typeof (a.length = '') == 'string' && a.length == 0"),
nxt_string("true") },

{ nxt_string("var a = [1]; "
"typeof (a.length = Object(2)) == 'object' && a.length == 2"),
nxt_string("true") },

{ nxt_string("var a = [1]; "
"typeof (a.length = Object('2')) == 'object'"),
nxt_string("true") },

{ nxt_string("var a = [1]; "
"a.length = { valueOf: () => 2 }; a.length == 2"),
nxt_string("true") },

{ nxt_string("var a = [1]; "
"a.length = { toString: () => '2' }; a.length == 2"),
nxt_string("true") },

{ nxt_string("var a = []; a.length = 0; JSON.stringify(a)"),
nxt_string("[]") },

Expand Down

0 comments on commit 0b4030f

Please sign in to comment.