Skip to content

Instantly share code, notes, and snippets.

@FlyingJester
Last active April 24, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlyingJester/03c7a0ae4a5d782d114b to your computer and use it in GitHub Desktop.
Save FlyingJester/03c7a0ae4a5d782d114b to your computer and use it in GitHub Desktop.
/////
// An implementation of the Sphere 1.x ByteArray object using only TypedArrays.
//
// Tested to work in SpiderMonkey and V8.
//
// Wrapper function to allow any TypedArray to 'become' a ByteArray.
function ByteArrayFromTypedArray(buffer){
var byteview;
if(buffer instanceof ArrayBuffer)
byteview = new Uint8Array(buffer);
else if(buffer instanceof Uint8Array)
byteview = buffer;
else
throw "Argument 0 is not a Harmony Typed Array.";
// Tack on the members needed for ByteArray.
Object.defineProperty(byteview, "length", {value:byteview.byteLength});
Object.defineProperty(byteview, "concat",
{value:function(a){
if(!(a instanceof Uint8Array))
throw "Argument 0 is not a ByteArray or a Harmony Typed Array.";
var thisArray = Array.apply([], this);
var otherArray = Array.apply([], a);
var cArray = thisArray.concat(otherArray);
var r = CreateByteArray(cArray.length);
for(var i = 0;i<cArray.length; i++)
r[i] = cArray[i];
return r;
}});
Object.defineProperty(byteview, "slice",
{value:function(a, e){
var thisArray = Array.apply([], this);
var sArray = thisArray.slice(a, e);
var r = CreateByteArray(sArray.length);
for(var i = 0;i<sArray.length; i++)
r[i] = sArray[i];
return r;
}});
return byteview;
}
function CreateByteArray(length){
var buffer = new ArrayBuffer(length);
var byteview = new Uint8Array(buffer);
return ByteArrayFromTypedArray(byteview);
}
function CreateByteArrayFromString(a){
var r = CreateByteArray(a.length);
for(var i = 0;i<a.length; i++)
r[i] = a.charCodeAt(i);
return r;
}
function CreateByteArrayFromString(a){
var r = CreateByteArray(a.length);
for(var i = 0;i<a.length; i++)
r[i] = a.charCodeAt(i);
return r;
}
function CreateStringFromByteArray(a){
if(!(a instanceof Uint8Array))
throw "Argument 0 is not a ByteArray or a Harmony Typed Array.";
var r = "";
var va = Array.apply([], a);
for(var i = 0;i<a.length; i++)
r += String.fromCharCode(va[i]);
return r;
}
@veso266
Copy link

veso266 commented Apr 24, 2017

Hi do you think you could tell me is there any ByteArray.js for ActionScript3 ByteArray (I am interested in writeUTPBytes and WriteInt function of AS3 byteArray)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment