Skip to content

Commit

Permalink
Testing using a TypedArray to emulate memory
Browse files Browse the repository at this point in the history
  • Loading branch information
arv committed Nov 6, 2013
1 parent 77f0ef1 commit 9b812c5
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
37 changes: 37 additions & 0 deletions experiments/typed-array-backing-test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!doctype html>
<script src="typed-array-backing.js"></script>
<script>

var p, c, c2;

if (typeof Node_set_firstChild !== 'undefined') {

p = new Node; // 1
c = new Node; // 7
// var c2 = new Node; // 13

// Emulate memory
Node_set_firstChild(1, 7);
Node_set_firstChild(7, 13);

console.assert(c.firstChild instanceof Node);

} else {
p = document.createElement('p');
c = p.appendChild(document.createElement('p'));
c2 = c.appendChild(document.createElement('p'));
}

function test() {
p.firstChild === c
c2 = c.firstChild
c2.firstChild === null;
}

console.profile('firstChild');
for (var i = 0; i < 1e7; i++) {
test();
}
console.profileEnd('firstChild');

</script>
66 changes: 66 additions & 0 deletions experiments/typed-array-backing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
(function() {
'use strict';

var MEMORY = new Uint32Array(1024);
var BUFFER = MEMORY.buffer;
var handles = [0];

var ptr = 1; // Keep 0 for null

function allocate(size) {
// Uint32Array.BYTES_PER_ELEMENT
var obj = new Uint32Array(BUFFER, ptr * 4, size);
var index = handles.length;
MEMORY[ptr] = index;
handles[index] = obj;
ptr += size;
return obj;
}

function Node_wrap(address) {
var obj = new Uint32Array(BUFFER, address * 4, NODE_SIZE);
obj.__proto__ = $Node_prototype;
return obj;
}

var HANDLE_OFFSET = 0
var PARENT_NODE_OFFSET = 1;
var FIRST_CHILD_OFFSET = 2;
var LAST_CHILD_OFFSET = 3;
var NEXT_SIBLING_OFFSET = 4;
var PREVIOUS_SIBLING_OFFSET = 5;
var NODE_SIZE = 6;

function Node_set_firstChild(parentAddress, childAddress) {
MEMORY[parentAddress + FIRST_CHILD_OFFSET] = childAddress;
}

function $Node() {
var self = allocate(NODE_SIZE);
self.__proto__ = $Node_prototype;
return self;
}

var $Node_prototype = $Node.prototype = {
get firstChild() {
// Type check. See instance-type-check.js
var address = this[2]; // FIRST_CHILD_OFFSET
if (!address)
return null;
var handleIndex = MEMORY[address];
if (handleIndex !== 0)
return handles[handleIndex];
var object = Node_wrap(address);
var handleIndex = handles.length;
handles[handleIndex] = object;
MEMORY[address] = handleIndex;
return object;
}
};

window.Node = $Node;

window.Node_set_firstChild = Node_set_firstChild;


})();

0 comments on commit 9b812c5

Please sign in to comment.