Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix array conversion when size changes dynamically #106

Merged
merged 1 commit into from May 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions py_mini_racer/extension/mini_racer_extension.cc
Expand Up @@ -447,20 +447,23 @@ static BinaryValue *convert_v8_to_binary(Isolate * isolate,

else if (value->IsArray()) {
Local<Array> arr = Local<Array>::Cast(value);
size_t len = arr->Length();
uint32_t len = arr->Length();

BinaryValue **ary = xalloc(ary, sizeof(*ary) * len);

res->type = type_array;
res->array_val = ary;
res->len = (size_t) len;

for(uint32_t i = 0; i < arr->Length(); i++) {
for(uint32_t i = 0; i < len; i++) {
Local<Value> element = arr->Get(context, i).ToLocalChecked();
BinaryValue *bin_value = convert_v8_to_binary(isolate, context, element);
if (bin_value == NULL) {
// adjust final array length
res->len = (size_t) i;
goto err;
}
ary[i] = bin_value;
res->len++;
}
}

Expand Down
80 changes: 80 additions & 0 deletions tests/test_array_growth.py
@@ -0,0 +1,80 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" Growing and reducing arrays """

import unittest
import json
import time

from datetime import datetime

from py_mini_racer import py_mini_racer


class Test(unittest.TestCase):
""" Test basic types """


def setUp(self):

self.mr = py_mini_racer.MiniRacer()

def test_growing_array(self):

js = """
var global_array = [
{
get first() {
for(var i=0; i<100; i++) {
global_array.push(0x41);
}
}
}
];

// when accessed, the first element will make the array grow by 100 items.
global_array;
"""

res = self.mr.eval(js)
# Initial array size was 100
self.assertEqual(res, [{'first': None}])


def test_shrinking_array(self):
js = """
var global_array = [
{
get first() {
for(var i=0; i<100; i++) {
global_array.pop();
}
}
}
];

// build a 200 elements array
for(var i=0; i < 200; i++)
global_array.push(0x41);

// when the first item will be accessed, it should remove 100 items.

global_array;
"""

# The final array should have:
# The initial item
# The next 100 items (value 0x41)
# The last 100 items which have been removed when the initial key was accessed
array = [{'first': None}] + \
[0x41] * 100 + \
[None] * 100

res = self.mr.eval(js)
self.assertEqual(res, array)


if __name__ == '__main__':
import sys
sys.exit(unittest.main())