Created
June 13, 2014 05:25
-
-
Save leeight/4c0e2b9d8ee2dd38710e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assumes little endian | |
// constants taken from http://nikic.github.com/2012/02/02/Pointer-magic-for-efficient-dynamic-value-representations.html | |
var MAXDOUBLE = 0xfff80000, | |
INT32TAG = 0xfff90000, | |
BOOLTAG = 0xfffa0000; | |
var heap = new ArrayBuffer(24), | |
f64 = new Float64Array(heap), | |
ui32 = new Uint32Array(heap), | |
i32 = new Int32Array(heap), | |
ui8 = new Uint8Array(heap); | |
function setInt32(index, value){ | |
var index32 = index << 1; // index is 8 bytes, we need to look at 4 bytes | |
i32[index32] = value >> 0; // store int32 | |
ui32[index32 + 1] = INT32TAG; // tag as int32 | |
} | |
function getInt32(index){ | |
var index32 = index << 1; | |
if (ui32[index32 + 1] === INT32TAG) { // check tag | |
return i32[index32]; // return int32 payload | |
} | |
throw new TypeError('Value is not an int32'); | |
} | |
function isInt32(index){ | |
return ui32[(index << 1) + 1] === INT32TAG; | |
} | |
function setBool(index, value){ | |
var index32 = index << 1; | |
ui32[index32] = value ? 1 : 0; | |
ui32[index32 + 1] = BOOLTAG; | |
} | |
function getBool(index){ | |
var index32 = index << 1; | |
if (ui32[index32 + 1] === BOOLTAG) { | |
return ui32[index32] ? true : false; | |
} | |
throw new TypeError('Value is not a boolean'); | |
} | |
function isBool(index){ | |
return ui32[(index << 1) + 1] === BOOLTAG; | |
} | |
function getType(index){ | |
var tag = ui32[(index << 1) + 1]; | |
if (tag <= MAXDOUBLE) { | |
return 'double'; | |
} | |
switch (tag) { | |
case INT32TAG: return 'int32'; | |
case BOOLTAG: return 'bool'; | |
} | |
throw new Error('not reached'); | |
} | |
function toHex(){ | |
return [].map.call(ui8, function(byte, i){ | |
return ('00'+byte.toString(16)).slice(-2) + ((i + 1) % 8 ? ' ' : '|'); | |
}).join('').slice(0, -1); | |
} | |
function types(){ | |
return [].map.call(f64, function(_, index){ | |
return getType(index); | |
}); | |
} | |
console.log(isInt32(1)); // false | |
setInt32(1, 10000); | |
console.log(isInt32(1)); // true | |
console.log(getInt32(1)); // 10000 | |
setBool(2, true); | |
console.log(types()); // [ 'double', 'int32', 'bool' ] | |
console.log(f64); // [ 0, NaN, NaN ] | |
console.log(toHex()); // 00 00 00 00 00 00 00 00|10 27 00 00 00 00 f9 ff|01 00 00 00 00 00 fa ff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment