-
Notifications
You must be signed in to change notification settings - Fork 0
/
strukt.min.mjs
1 lines (1 loc) · 2.66 KB
/
strukt.min.mjs
1
const base_types={u8:[1,Number,DataView.prototype.getUint8,DataView.prototype.setUint8],u16:[2,Number,DataView.prototype.getUint16,DataView.prototype.setUint16],u32:[4,Number,DataView.prototype.getUint32,DataView.prototype.setUint32],u64:[8,BigInt,DataView.prototype.getBigUint64,DataView.prototype.setBigUint64],s8:[1,Number,DataView.prototype.getInt8,DataView.prototype.setInt8],s16:[2,Number,DataView.prototype.getInt16,DataView.prototype.setInt16],s32:[4,Number,DataView.prototype.getInt32,DataView.prototype.setInt32],s64:[8,BigInt,DataView.prototype.getBigInt64,DataView.prototype.setBigInt64],f32:[4,Number,DataView.prototype.getFloat32,DataView.prototype.setFloat32],f64:[8,Number,DataView.prototype.getFloat64,DataView.prototype.setFloat64]};export const field_types_data={...base_types,bool:base_types.u8,boolean:base_types.u8,char:base_types.u8,byte:base_types.u8,uchar:base_types.u8,ubyte:base_types.u8,i8:base_types.s8,size16:base_types.u16,ptr16:base_types.u16,i16:base_types.s16,ptr32:base_types.u32,size32:base_types.u32,i32:base_types.s32,ptr64:base_types.u64,size64:base_types.u64,ptr:base_types.u64,size:base_types.u64,str:base_types.u64,string:base_types.u64,i64:base_types.s64,float:base_types.f32,float32:base_types.f32,float64:base_types.f64,double:base_types.f64};export const getFieldTypeData=e=>field_types_data["string"==typeof e?e:e[0]];export const getFieldTypeSize=e=>"string"==typeof e?field_types_data[e][0]:field_types_data[e[0]][0]*e[1];export class Strukt{constructor(e,t){this.name=e,this.innerschema=new Map;for(let[e,s]of Array.isArray(t)?t:Object.entries(t))this.innerschema.set(e,s)}get schema(){return{...this.innerschema.entries()}}get size(){return[...this.innerschema.entries()].reduce(((e,[,t])=>e+getFieldTypeSize(t)),0)}typeOf(e){if(this.innerschema.has(e))return this.innerschema.get(e);console.assert(!1,"field not found")}sizeOf(e){if(this.innerschema.has(e))return getFieldTypeSize(this.innerschema.get(e));console.assert(!1,"field not found")}offsetOf(e){if(this.innerschema.has(e))return console.assert(!1,"not implemented"),0;console.assert(!1,"field not found")}write(e,t){return this.writeTo(new ArrayBuffer(this.size),e,0,t)}writeTo(e,t,s=0,a){const i=new DataView(e);for(let[e,r]of this.innerschema.entries()){const o="string"!=typeof r&&r[1]>1,p=o?r[1]:1,[n,y,u,l]=getFieldTypeData(r),f=o?t[e]:[t[e]];for(let e=0;e<p;++e)l.call(i,s,y(f[e]),a),s+=n}return e}readFrom(e,t=0,s=null,a){const i=new DataView(e),r=[];for(let e=0;e<(s??1);++e){const e={};for(let[s,r]of this.innerschema.entries()){const o="string"!=typeof r&&r[1]>1,p=o?r[1]:1,[n,y,u,l]=getFieldTypeData(r),f=[];for(let e=0;e<p;++e)f.push(y(u.call(i,t,a))),t+=n;e[s]=o?f:f[0]}r.push(e)}return null==s?r[0]:r}}