UNPKG

wowok

Version:

Wowok Blockchain TypeScript API

1 lines 2.53 kB
import{ulebEncode}from'./uleb.js';import{encodeStr}from'./utils.js';export class BcsWriter{['dataView'];['bytePosition']=0x0;['size'];['maxSize'];['allocateSize'];constructor({initialSize:initialSize=0x400,maxSize:maxSize=Infinity,allocateSize:allocateSize=0x400}={}){this['size']=initialSize,this['maxSize']=maxSize,this['allocateSize']=allocateSize,this['dataView']=new DataView(new ArrayBuffer(initialSize));}['ensureSizeOrGrow'](a){const b=this['bytePosition']+a;if(b>this['size']){const c=Math['min'](this['maxSize'],Math['max'](this['size']+b,this['size']+this['allocateSize']));if(b>c)throw new Error('Attempting\x20to\x20serialize\x20to\x20BCS,\x20but\x20buffer\x20does\x20not\x20have\x20enough\x20size.\x20Allocated\x20size:\x20'+this['size']+',\x20Max\x20size:\x20'+this['maxSize']+',\x20Required\x20size:\x20'+b);this['size']=c;const d=new ArrayBuffer(this['size']);new Uint8Array(d)['set'](new Uint8Array(this['dataView']['buffer'])),this['dataView']=new DataView(d);}}['shift'](a){return this['bytePosition']+=a,this;}['write8'](a){return this['ensureSizeOrGrow'](0x1),this['dataView']['setUint8'](this['bytePosition'],Number(a)),this['shift'](0x1);}['writeBytes'](a){this['ensureSizeOrGrow'](a['length']);for(let b=0x0;b<a['length'];b++){this['dataView']['setUint8'](this['bytePosition']+b,a[b]);}return this['shift'](a['length']);}['write16'](a){return this['ensureSizeOrGrow'](0x2),this['dataView']['setUint16'](this['bytePosition'],Number(a),!![]),this['shift'](0x2);}['write32'](a){return this['ensureSizeOrGrow'](0x4),this['dataView']['setUint32'](this['bytePosition'],Number(a),!![]),this['shift'](0x4);}['write64'](a){return toLittleEndian(BigInt(a),0x8)['forEach'](b=>this['write8'](b)),this;}['write128'](a){return toLittleEndian(BigInt(a),0x10)['forEach'](b=>this['write8'](b)),this;}['write256'](a){return toLittleEndian(BigInt(a),0x20)['forEach'](b=>this['write8'](b)),this;}['writeULEB'](a){return ulebEncode(a)['forEach'](b=>this['write8'](b)),this;}['writeVec'](a,b){return this['writeULEB'](a['length']),Array['from'](a)['forEach']((c,d)=>b(this,c,d,a['length'])),this;}*[Symbol['iterator']](){for(let a=0x0;a<this['bytePosition'];a++){yield this['dataView']['getUint8'](a);}return this['toBytes']();}['toBytes'](){return new Uint8Array(this['dataView']['buffer']['slice'](0x0,this['bytePosition']));}['toString'](a){return encodeStr(this['toBytes'](),a);}}function toLittleEndian(a,b){const c=new Uint8Array(b);let d=0x0;while(a>0x0){c[d]=Number(a%BigInt(0x100)),a=a/BigInt(0x100),d+=0x1;}return c;}