Skip to content

Instantly share code, notes, and snippets.

@FelixWolf
Created August 23, 2016 14:00
Show Gist options
  • Save FelixWolf/8e13427d9b55f51348108a5d3d25689f to your computer and use it in GitHub Desktop.
Save FelixWolf/8e13427d9b55f51348108a5d3d25689f to your computer and use it in GitHub Desktop.
Struct for Javascript, based on Python struct. (In development)
var struct = new (function(){
var dLen = {
/*"Type": [Size, Read, Write]*/
/*pad byte */"x": [1, "getUint8", "setUint8"],
/*char */"c": [1, "getUint8", "setUint8"],
/*signed char */"b": [1, "getInt8", "setInt8"],
/*unsigned char */"B": [1, "getUint8", "setUint8"],
/*_Bool */"?": [1, "getUint8", "setUint8"],
/*short */"h": [2, "getInt16", "getInt16"],
/*unsigned short */"H": [2, "getUint16", "getUint16"],
/*int */"i": [4, "getInt32", "getInt32"],
/*unsigned int */"I": [4, "getUint32", "getUint32"],
/*long */"l": [4, "getInt32", "getInt32"],
/*unsigned long */"L": [4, "getUint32", "getUint32"],
/*long long */"q": [8, "", ""],
/*unsigned long long*/"Q": [8, "", ""],
/*ssize_t */"n": [8, "", ""],
/*size_t */"N": [8, "", ""],
/*float */"f": [4, "getFloat32", "setFloat32"],
/*double */"d": [8, "getFloat64", "setFloat64"],
/*char[] */"s": [1, "", ""],
/*char[] */"p": [1, "", ""],
/*void * */"P": [8, "", ""],
">": [0, "", ""],
"<": [0, "", ""],
"!": [0, "", ""],
"@": [0, "", ""]
};
function getDataView(blah){
if(blah.constructor === DataView)
return blah;
if(typeof(blah) === "string"){
var a = new TextEncoder("utf-8").encode("asdf")
var b = new DataView(new ArrayBuffer(a.length));
for(var i=0,l=a.length;i<l;i++){
b.setUint8(i, a[i])
}
return b;
}
if(Array.isArray(blah)){
var b = new DataView(new ArrayBuffer(blah.length));
for(var i=0,l=blah.length;i<l;i++){
b.setUint8(i, blah[i])
}
return b;
}
}
this.calcsize = function(fmt){
var size = 0, calcdsize = 0;
for(var i=0,l=fmt.length;i<l;i++){
if(!isNaN(parseInt(fmt[i]))){
if(size == 0){
size = parseInt(fmt[i]);
}else{
size = (size*10)+parseInt(fmt[i]);
}
}else{
if(size == 0)size = 1;
if(fmt[i] in dLen){
calcdsize += dLen[fmt[i]][0]*size;
}else{
throw "bad char in struct format";
}
size = 0;
}
}
return calcdsize;
};
/*fmt, v1, v2, ...*/
this.pack = function(){
if(arguments.length == 0)
throw "bad char in struct format";
var fmt = arguments[0], size = 0;
var result = new DataView(new ArrayBuffer(self.calcsize(fmt)));
for(var i=0,l=fmt.length;i<l;i++){
if(!isNaN(parseInt(fmt[i]))){
if(size == 0) size = parseInt(fmt[i]);
else size = (size*10)+parseInt(fmt[i]);
}else{
if(size == 0)size = 1;
if(fmt[i] == ""){
}else if(fmt[i] in dLen){
calcdsize += dLen[fmt[i]][0]*size;
}else{
throw "bad char in struct format";
}
size = 0;
}
}
return calcdsize;
};
});
var a = new TextEncoder("utf-8").encode("asdf")
var b = new DataView(new ArrayBuffer(a.length));
for(var i=0,l=a.length;i<l;i++){
b.setUint8(i, a[i])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment