diff --git a/dist/index.cjs b/dist/index.cjs index b7eaa36..2a4497f 100644 --- a/dist/index.cjs +++ b/dist/index.cjs @@ -1,2 +1,2 @@ -class TinybufError extends Error{}function $hashCode(t){let r=5381;for(let e=0;ethis.on(t,(()=>{})))),this}clear(){this.t.clear(),this.o.clear()}}const t=Math.floor,r=Math.ceil,$clamp=(t,r,e)=>t>e?e:te<0?r(e):t(e),$roundAwayFromZero=e=>e<0?t(e):r(e);function $touscal8(t){return $clamp(127+$roundTowardZero(254*t-127),0,254)}function $toscal8(t){return $clamp($roundTowardZero(127*t),-127,127)+127}function $fromuscal8(t){return $clamp(.01*($roundAwayFromZero(.3937007874015748*(t-127))+50),0,1)}function $fromscal8(t){return $clamp(.01*$roundAwayFromZero(.787401574803149*(t-127)),-1,1)}const e={UInt:"uint",UInt8:"u8",UInt16:"u16",UInt32:"u32",Int:"int",Int8:"i8",Int16:"i16",Int32:"i32",Float64:"f64",Float32:"f32",Float16:"f16",BFloat16:"b16",Scalar8:"sc",UScalar8:"usc",Bool:"bl",Bools:"bls",Buffer:"buf",String:"str",JSON:"jsn",RegExp:"re",Date:"dt"},i=Object.values(e);class MaybeType{constructor(t){this.type=t}}const mask=(t,r=1)=>t.reduce(((t,r)=>t<<1|r),r),unmask=(t,r)=>{const e=void 0===r?31-Math.clz32(t):Array.isArray(r)?r.length:r,i=Array.isArray(r)&&r.length===e?r:new Array(e);for(let r=0;rt.encode(r)}(),s=function(){const t=new TextDecoder("utf-8");return r=>t.decode(r)}();const o=function(){const t=new Float32Array(1),r=new Int32Array(t.buffer);return function(e){t[0]=e;let i=r[0],n=i>>16&32768,s=4096+(2147483647&i)|0;return s>=1199570944?(2147483647&i)<1199570944?31743|n:s<2139095040?31744|n:31744|n|(8388607&i)>>13:s>=947912704?n|s-939524096>>13:s<855638016?n:(s=(2147483647&i)>>23,n|(8388607&i|8388608)+(8388608>>>s-102)>>126-s)}}(),h=function(){const t=Math.pow(2,-24),r=new Float32Array(1056);for(let t=0;t<32;t++)r[t]=Math.pow(2,t-15);for(let t=0;t<1024;t++)r[t+32]=1+t/1024;return function(e){const i=32768&~e?1:-1,n=31744&e,s=1023&e;return 0===n?0===s?0*i:i*t:31744===n?0===s?i*(1/0):NaN:r[n>>10]*r[s+32]*i}}(),a=new Uint32Array(1),f=new Float32Array(a.buffer);const u=536870912,c=268435456,d=4294967296,l={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r<0&&(r=0),r<128?e.u(r):r<16384?e.l(r+32768):r=u?(e.$(t(r/d)+3758096384),e.$(r>>>0)):e.u(!0===r?1:0)},p:t=>{const r=t.m();return 128&r?64&r?32&r?(t.v()-3758096384)*d+t.v():t.v()-3221225472:t.B()-32768:(t.F(),r)}},$={h:(t,r)=>r.u(t),p:t=>t.A()},w={h:(t,r)=>r.l(t),p:t=>t.B()},y={h:(t,r)=>r.$(t),p:t=>t.v()},p={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r>=-64&&r<64?e.u(127&r):r>=-8192&&r<8192?e.l(32768+(16383&r)):r>=-268435456&&r=c?(e.$(3758096384+(536870911&t(r/d))),e.$(r>>>0)):e.u(!0===r?127:0)},p:t=>{let r,e=t.m();return 128&e?64&e?32&e?(r=t.v()-3758096384,r=268435456&r?3758096384|r:r,r*d+t.v()):(r=t.v()-3221225472,268435456&r?3758096384|r:r):(r=t.B()-32768,8192&r?4294950912|r:r):(t.F(),64&e?4294967168|e:e)}},b={h:(t,r)=>r.T(t),p:t=>t.U()},m={h:(t,r)=>r.I(t),p:t=>t.M()},v={h:(t,r)=>r.S(t),p:t=>t._()},B={h:(t,r)=>r.l(function $tobf16(t){return f[0]=t,a[0]>>>16}(t)),p:t=>function $frombf16(t){return a[0]=t<<16,f[0]}(t.B())},F={h:(t,r)=>r.l(o(t)),p:t=>h(t.B())},A={h:(t,r)=>r.j(t),p:t=>t.H()},T={h:(t,r)=>r.k(t),p:t=>t.O()},x={h:(t,r)=>r.u($touscal8(t)),p:t=>$fromuscal8(t.A())},E={h:(t,r)=>r.u($toscal8(t)),p:t=>$fromscal8(t.A())},g={h:(t,r)=>p.h(t.getTime(),r),p:t=>new Date(p.p(t))},U={h:(t,r)=>{l.h(t.byteLength,r),r.C(t)},p:t=>t.D(l.p(t))},I={h:(t,r)=>U.h(n(t),r),p:t=>s(U.p(t))},M={h:(t,r)=>r.u(t?1:0),p:t=>0!==t.A()},S={h:(t,r)=>{t.length>28&&(t=t.slice(0,28)),l.h(mask(t),r)},p:(t,r)=>unmask(l.p(t),r)},_={h:(t,r)=>I.h(JSON.stringify(t),r),p:t=>JSON.parse(I.p(t))},j={h:(t,r)=>{r.u(mask([t.global,t.ignoreCase,t.multiline])),I.h(t.source,r)},p:t=>{const[r,e,i]=unmask(t.A());return new RegExp(I.p(t),(r?"g":"")+(e?"i":"")+(i?"m":""))}},H={[e.UInt]:l.h,[e.UInt8]:$.h,[e.UInt16]:w.h,[e.UInt32]:y.h,[e.Int]:p.h,[e.Int8]:b.h,[e.Int16]:m.h,[e.Int32]:v.h,[e.Float64]:T.h,[e.Float32]:A.h,[e.Float16]:F.h,[e.BFloat16]:B.h,[e.Scalar8]:E.h,[e.UScalar8]:x.h,[e.Bool]:M.h,[e.Bools]:S.h,[e.Buffer]:U.h,[e.String]:I.h,[e.JSON]:_.h,[e.RegExp]:j.h,[e.Date]:g.h},k={[e.UInt]:l.p,[e.UInt8]:$.p,[e.UInt16]:w.p,[e.UInt32]:y.p,[e.Int]:p.p,[e.Int8]:b.p,[e.Int16]:m.p,[e.Int32]:v.p,[e.Float64]:T.p,[e.Float32]:A.p,[e.Float16]:F.p,[e.BFloat16]:B.p,[e.Scalar8]:E.p,[e.UScalar8]:x.p,[e.Bool]:M.p,[e.Bools]:S.p,[e.Buffer]:U.p,[e.String]:I.p,[e.JSON]:_.p,[e.RegExp]:j.p,[e.Date]:g.p};let O={safe:!1,useGlobalEncodingBuffer:!0,encodingBufferMaxSize:1500,encodingBufferInitialSize:256,encodingBufferIncrement:256};class BufferWriter{constructor(t){this.R=0,this.V=0,this.N="number"==typeof t;let r=t instanceof Uint8Array?t:new Uint8Array(t);this.W=r,this.J=r.byteOffset,this.P=new DataView(r.buffer)}q(t){return this.P.buffer!==t.buffer&&(this.P=new DataView(t.buffer)),this.W=t,this.J=t.byteOffset,this.N=!1,this.V=0,this.R=0,this}G(){return this.W.subarray(0,this.R)}L(){const t=new Uint8Array(this.R);return t.set(this.G()),t}T(t){this.K(1).setInt8(this.V,t)}I(t){this.K(2).setInt16(this.V,t,!0)}S(t){this.K(4).setInt32(this.V,t,!0)}u(t){this.K(1).setUint8(this.V,t)}l(t){this.K(2).setUint16(this.V,t,!1)}$(t){this.K(4).setUint32(this.V,t,!1)}j(t){this.K(4).setFloat32(this.V,t,!0)}k(t){this.K(8).setFloat64(this.V,t,!0)}C(t){this.K(t.byteLength),this.W.set(t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this.V-this.J)}K(t){return this.R+t>this.W.byteLength&&this.X(t),this.V=this.J+this.R,this.R+=t,this.P}X(t){if(!this.N)throw new TinybufError("exceeded buffer length: "+this.W.byteLength);const r=this.W.byteLength,e=this.R+t-r,i=O.encodingBufferMaxSize-r;if(e>i)throw new TinybufError("exceeded encodingBufferMaxSize: "+O.encodingBufferMaxSize);const n=O.encodingBufferIncrement,s=Math.ceil(e/n)*n,o=r+Math.min(s,i),h=new Uint8Array(o);h.set(this.W),this.P=new DataView(h.buffer),this.W=h,this.J=0}}class BufferReader{constructor(t,r){this.q(t,r)}q(t,r){const e=ArrayBuffer.isView(t),i=e?t.buffer:t,n=e?t.byteOffset:0;let s=this.P;return(void 0===s||s.buffer!==i||ns.byteOffset+s.byteLength)&&(s=this.P=t instanceof DataView?t:new DataView(i)),this.J=n-s.byteOffset,this.Y=t.byteLength,this.i=null!=r?r:0,this}m(){if(this.i>=this.Y)throw new RangeError("exceeded bytes");return this.P.getUint8(this.J+this.i)}F(){this.i++}A(){return this.P.getUint8(this.Z(1))}B(){return this.P.getUint16(this.Z(2))}v(){return this.P.getUint32(this.Z(4))}U(){return this.P.getInt8(this.Z(1))}M(){return this.P.getInt16(this.Z(2),!0)}_(){return this.P.getInt32(this.Z(4),!0)}H(){return this.P.getFloat32(this.Z(4),!0)}O(){return this.P.getFloat64(this.Z(8),!0)}D(t){return new Uint8Array(this.P.buffer,this.P.byteOffset+this.Z(t),t)}Z(t){const r=this.i;if(r+t>this.Y)throw new RangeError("exceeded bytes");return this.i=r+t,this.J+r}}class BufferFormat{constructor(t,r){if(this.tt=!1,"string"==typeof t&&i.includes(t))this.rt=t;else{if(t instanceof MaybeType)throw new TypeError("Format cannot be optional");if(!(t instanceof Object))throw new TypeError("Format must be object or Type");if(this.rt=void 0,this.et=new Map,this.it=Object.keys(t).map((r=>{const e=new Field(r,t[r]);return this.et.set(r,e),e})),void 0===r)this.header=$hashCode(this.f),this.nt=this.header;else if(null===r)this.header=void 0,this.nt=void 0;else{if(!function isValidHeader(t){return"number"==typeof t?Number.isInteger(t)&&t>=0&&t<=65535:"string"==typeof t&&2===(new TextEncoder).encode(t).byteLength}(r))throw new TypeError("Header must be 2-byte string, uint16, or null.");this.header=r,this.nt="number"==typeof r?r:$strToHashCode(r)}}}get f(){return void 0===this.st&&(this.st=void 0!==this.it?`{${this.it.map((t=>t.f)).join(",")}}`:`${this.rt}`),this.st}static ot(){return O.useGlobalEncodingBuffer?(BufferFormat.ht||(this.ht=new BufferWriter(O.encodingBufferMaxSize)),this.ht):new BufferWriter(O.encodingBufferInitialSize)}encodeInto(t,r){return r.subarray(0,this.encodeIntoLength(t,r))}encodeIntoLength(t,r){var e,i;this.tt&&(t=this.ft(t));const n=null!==(i=null===(e=this.ut)||void 0===e?void 0:e.q(r))&&void 0!==i?i:new BufferWriter(r);this.ut=void 0;try{return this.ct(t,n),n.R}finally{this.ut=n}}encode(t,r){return this.dt||(this.dt=BufferFormat.ot()),this.dt.R=0,this.tt&&(t=this.ft(t)),this.ct(t,this.dt),(null!=r?r:O.safe)?this.dt.L():this.dt.G()}decodeInto(t,r){return this.lt(t,r)}decode(t,r){return this.lt(t,r)}setTransforms(t){if(this.tt=!0,"function"==typeof t||Array.isArray(t)&&"function"==typeof t[0])this.$t=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set transforms for field '${r}'`);e.wt.setTransforms(t[r])}return this}setValidation(t){if(this.tt=!0,"function"==typeof t)this.yt=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set validation function for field '${r}'`);e.wt.setValidation(t[r])}return this}lt(t,r){var e,i;const n=void 0===this.header?0:2,s=null!==(i=null===(e=this.bt)||void 0===e?void 0:e.q(t,n))&&void 0!==i?i:new BufferReader(t,n);this.bt=void 0;try{return this.vt(s,r)}finally{this.bt=s}}ct(t,r){if(void 0!==this.nt&&r.l(this.nt),void 0!==this.rt){const e=this.yt||this.$t?this.ft(t):t;return H[this.rt](e,r)}if("object"!=typeof t||!t)throw new TypeError("expected object type");for(const e of this.it){const i=t[e.Bt];if(e.Ft){if(null==i){M.h(!1,r);continue}M.h(!0,r)}else if(null==i)throw new Error(`missing required value: ${e.Bt}`);e.At?this.Tt(i,r,e.wt):e.wt.ct(i,r)}}ft(t){return this.yt&&this.xt(t),"function"==typeof this.$t?this.$t(t):Array.isArray(this.$t)&&"function"==typeof this.$t[0]?this.$t[0](t):t}Et(t){return Array.isArray(this.$t)&&"function"==typeof this.$t[1]&&(t=this.$t[1](t)),this.yt&&this.xt(t),t}xt(t){if(!this.yt)return;const r=this.yt(t);if(r instanceof Error)throw r;if(!1===r)throw new Error("failed validation")}vt(t,r){return this.vt=this.gt(),this.vt(t,r)}Ut(){const t=this.it.map((({Bt:t},r)=>`v.${t}=this.${this.It.name}(${r},s,v.${t})`)).join(";");return`let v=o??{};${t};return v;`}It(t,r,e){const i=this.it[t];if(!i.Ft||M.p(r))return i.At?this.Mt(i.wt,r,e):i.wt.vt(r,e)}gt(){return void 0!==this.rt?this.tt?t=>this.Et(k[this.rt](t)):k[this.rt]:new Function("s","o",this.Ut())}Tt(t,r,e){if(!Array.isArray(t))throw new TypeError(`expected array, instead got: ${t}`);l.h(t.length,r);for(let i=0;inew BufferParser,exports.defineFormat=function defineFormat(t,r){return null!==t&&"object"==typeof t?new BufferFormat(t):new BufferFormat(r,t)},exports.f16round=function f16round(t){return h(o(t))},exports.mask=mask,exports.optional=function optional(t){return new MaybeType(t)},exports.peekHeader=peekHeader,exports.peekHeaderStr=peekHeaderStr,exports.scalround=function scalround(t){return $fromscal8($toscal8(t))},exports.setTinybufConfig=t=>{O=Object.assign(Object.assign({},O),t)},exports.unmask=unmask,exports.uscalround=function uscalround(t){return $fromuscal8($touscal8(t))}; +class TinybufError extends Error{}function $hashCode(t){let r=5381;for(let e=0;ethis.on(t,(()=>{})))),this}clear(){this.t.clear(),this.o.clear()}}const t=Math.floor,r=Math.ceil,$clamp=(t,r,e)=>t>e?e:te<0?r(e):t(e),$roundAwayFromZero=e=>e<0?t(e):r(e);function $touscal8(t){return $clamp(127+$roundTowardZero(254*t-127),0,254)}function $toscal8(t){return $clamp($roundTowardZero(127*t),-127,127)+127}function $fromuscal8(t){return $clamp(.01*($roundAwayFromZero(.3937007874015748*(t-127))+50),0,1)}function $fromscal8(t){return $clamp(.01*$roundAwayFromZero(.787401574803149*(t-127)),-1,1)}const e={UInt:"uint",UInt8:"u8",UInt16:"u16",UInt32:"u32",Int:"int",Int8:"i8",Int16:"i16",Int32:"i32",Float64:"f64",Float32:"f32",Float16:"f16",BFloat16:"b16",Scalar8:"sc",UScalar8:"usc",Bool:"bl",Bools:"bls",Buffer:"buf",String:"str",JSON:"jsn",RegExp:"re",Date:"dt"},i=Object.values(e);class MaybeType{constructor(t){this.type=t}}const mask=(t,r=1)=>t.reduce(((t,r)=>t<<1|r),r),unmask=(t,r)=>{const e=void 0===r?31-Math.clz32(t):Array.isArray(r)?r.length:r,i=Array.isArray(r)&&r.length===e?r:new Array(e);for(let r=0;rt.encode(r)}(),s=function(){const t=new TextDecoder("utf-8");return r=>t.decode(r)}();const o=function(){const t=new Float32Array(1),r=new Int32Array(t.buffer);return function(e){t[0]=e;let i=r[0],n=i>>16&32768,s=4096+(2147483647&i)|0;return s>=1199570944?(2147483647&i)<1199570944?31743|n:s<2139095040?31744|n:31744|n|(8388607&i)>>13:s>=947912704?n|s-939524096>>13:s<855638016?n:(s=(2147483647&i)>>23,n|(8388607&i|8388608)+(8388608>>>s-102)>>126-s)}}(),h=function(){const t=Math.pow(2,-24),r=new Float32Array(1056);for(let t=0;t<32;t++)r[t]=Math.pow(2,t-15);for(let t=0;t<1024;t++)r[t+32]=1+t/1024;return function(e){const i=32768&~e?1:-1,n=31744&e,s=1023&e;return 0===n?0===s?0*i:i*t:31744===n?0===s?i*(1/0):NaN:r[n>>10]*r[s+32]*i}}(),a=new Uint32Array(1),f=new Float32Array(a.buffer);const u=536870912,c=268435456,d=4294967296,l={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r<0&&(r=0),r<128?e.u(r):r<16384?e.l(r+32768):r=u?(e.$(t(r/d)+3758096384|0),e.l(r>>>16),e.l(65535&r)):e.u(!0===r?1:0)},p:t=>{const r=t.m();return 128&r?64&r?32&r?(t.v()-3758096384)*d+t.v():t.v()-3221225472:t.B()-32768:(t.F(),r)}},$={h:(t,r)=>r.u(t),p:t=>t.A()},w={h:(t,r)=>r.l(t),p:t=>t.B()},y={h:(t,r)=>r.$(t),p:t=>t.v()},p={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r>=-64&&r<64?e.u(127&r):r>=-8192&&r<8192?e.l(32768+(16383&r)):r>=-268435456&&r=c?(e.$(536870911&t(r/d)|3758096384),e.l(r>>>16),e.l(65535&r)):e.u(!0===r?127:0)},p:t=>{let r,e=t.m();return 128&e?64&e?32&e?(r=t.v()-3758096384,r=268435456&r?3758096384|r:r,r*d+t.v()):(r=t.v()-3221225472,268435456&r?3758096384|r:r):(r=t.B()-32768,8192&r?4294950912|r:r):(t.F(),64&e?4294967168|e:e)}},b={h:(t,r)=>r.T(t),p:t=>t.U()},m={h:(t,r)=>r.I(t),p:t=>t.M()},v={h:(t,r)=>r.S(t),p:t=>t._()},B={h:(t,r)=>r.l(function $tobf16(t){return f[0]=t,a[0]>>>16}(t)),p:t=>function $frombf16(t){return a[0]=t<<16,f[0]}(t.B())},F={h:(t,r)=>r.l(o(t)),p:t=>h(t.B())},A={h:(t,r)=>r.j(t),p:t=>t.H()},T={h:(t,r)=>r.k(t),p:t=>t.O()},x={h:(t,r)=>r.u($touscal8(t)),p:t=>$fromuscal8(t.A())},E={h:(t,r)=>r.u($toscal8(t)),p:t=>$fromscal8(t.A())},g={h:(t,r)=>p.h(t.getTime(),r),p:t=>new Date(p.p(t))},U={h:(t,r)=>{l.h(t.byteLength,r),r.C(t)},p:t=>t.D(l.p(t))},I={h:(t,r)=>U.h(n(t),r),p:t=>s(U.p(t))},M={h:(t,r)=>r.u(t?1:0),p:t=>0!==t.A()},S={h:(t,r)=>{t.length>28&&(t=t.slice(0,28)),l.h(mask(t),r)},p:(t,r)=>unmask(l.p(t),r)},_={h:(t,r)=>I.h(JSON.stringify(t),r),p:t=>JSON.parse(I.p(t))},j={h:(t,r)=>{r.u(mask([t.global,t.ignoreCase,t.multiline])),I.h(t.source,r)},p:t=>{const[r,e,i]=unmask(t.A());return new RegExp(I.p(t),(r?"g":"")+(e?"i":"")+(i?"m":""))}},H={[e.UInt]:l.h,[e.UInt8]:$.h,[e.UInt16]:w.h,[e.UInt32]:y.h,[e.Int]:p.h,[e.Int8]:b.h,[e.Int16]:m.h,[e.Int32]:v.h,[e.Float64]:T.h,[e.Float32]:A.h,[e.Float16]:F.h,[e.BFloat16]:B.h,[e.Scalar8]:E.h,[e.UScalar8]:x.h,[e.Bool]:M.h,[e.Bools]:S.h,[e.Buffer]:U.h,[e.String]:I.h,[e.JSON]:_.h,[e.RegExp]:j.h,[e.Date]:g.h},k={[e.UInt]:l.p,[e.UInt8]:$.p,[e.UInt16]:w.p,[e.UInt32]:y.p,[e.Int]:p.p,[e.Int8]:b.p,[e.Int16]:m.p,[e.Int32]:v.p,[e.Float64]:T.p,[e.Float32]:A.p,[e.Float16]:F.p,[e.BFloat16]:B.p,[e.Scalar8]:E.p,[e.UScalar8]:x.p,[e.Bool]:M.p,[e.Bools]:S.p,[e.Buffer]:U.p,[e.String]:I.p,[e.JSON]:_.p,[e.RegExp]:j.p,[e.Date]:g.p};let O={safe:!1,useGlobalEncodingBuffer:!0,encodingBufferMaxSize:1500,encodingBufferInitialSize:256,encodingBufferIncrement:256};class BufferWriter{constructor(t){this.R=0,this.V=0,this.N="number"==typeof t;let r=t instanceof Uint8Array?t:new Uint8Array(t);this.W=r,this.J=r.byteOffset,this.P=new DataView(r.buffer)}q(t){return this.P.buffer!==t.buffer&&(this.P=new DataView(t.buffer)),this.W=t,this.J=t.byteOffset,this.N=!1,this.V=0,this.R=0,this}G(){return this.W.subarray(0,this.R)}L(){const t=new Uint8Array(this.R);return t.set(this.G()),t}T(t){this.K(1).setInt8(this.V,t)}I(t){this.K(2).setInt16(this.V,t,!0)}S(t){this.K(4).setInt32(this.V,t,!0)}u(t){this.K(1).setUint8(this.V,t)}l(t){this.K(2).setUint16(this.V,t,!1)}$(t){this.K(4).setUint32(this.V,t,!1)}j(t){this.K(4).setFloat32(this.V,t,!0)}k(t){this.K(8).setFloat64(this.V,t,!0)}C(t){this.K(t.byteLength),this.W.set(t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this.V-this.J)}K(t){return this.R+t>this.W.byteLength&&this.X(t),this.V=this.J+this.R,this.R+=t,this.P}X(t){if(!this.N)throw new TinybufError("exceeded buffer length: "+this.W.byteLength);const r=this.W.byteLength,e=this.R+t-r,i=O.encodingBufferMaxSize-r;if(e>i)throw new TinybufError("exceeded encodingBufferMaxSize: "+O.encodingBufferMaxSize);const n=O.encodingBufferIncrement,s=Math.ceil(e/n)*n,o=r+Math.min(s,i),h=new Uint8Array(o);h.set(this.W),this.P=new DataView(h.buffer),this.W=h,this.J=0}}class BufferReader{constructor(t,r){this.q(t,r)}q(t,r){const e=ArrayBuffer.isView(t),i=e?t.buffer:t,n=e?t.byteOffset:0;let s=this.P;return(void 0===s||s.buffer!==i||ns.byteOffset+s.byteLength)&&(s=this.P=t instanceof DataView?t:new DataView(i)),this.J=n-s.byteOffset,this.Y=t.byteLength,this.i=null!=r?r:0,this}m(){if(this.i>=this.Y)throw new RangeError("exceeded bytes");return this.P.getUint8(this.J+this.i)}F(){this.i++}A(){return this.P.getUint8(this.Z(1))}B(){return this.P.getUint16(this.Z(2))}v(){return this.P.getUint32(this.Z(4))}U(){return this.P.getInt8(this.Z(1))}M(){return this.P.getInt16(this.Z(2),!0)}_(){return this.P.getInt32(this.Z(4),!0)}H(){return this.P.getFloat32(this.Z(4),!0)}O(){return this.P.getFloat64(this.Z(8),!0)}D(t){return new Uint8Array(this.P.buffer,this.P.byteOffset+this.Z(t),t)}Z(t){const r=this.i;if(r+t>this.Y)throw new RangeError("exceeded bytes");return this.i=r+t,this.J+r}}class BufferFormat{constructor(t,r){if(this.tt=!1,"string"==typeof t&&i.includes(t))this.rt=t;else{if(t instanceof MaybeType)throw new TypeError("Format cannot be optional");if(!(t instanceof Object))throw new TypeError("Format must be object or Type");if(this.rt=void 0,this.et=new Map,this.it=Object.keys(t).map((r=>{const e=new Field(r,t[r]);return this.et.set(r,e),e})),void 0===r)this.header=$hashCode(this.f),this.nt=this.header;else if(null===r)this.header=void 0,this.nt=void 0;else{if(!function isValidHeader(t){return"number"==typeof t?Number.isInteger(t)&&t>=0&&t<=65535:"string"==typeof t&&2===(new TextEncoder).encode(t).byteLength}(r))throw new TypeError("Header must be 2-byte string, uint16, or null.");this.header=r,this.nt="number"==typeof r?r:$strToHashCode(r)}}}get f(){return void 0===this.st&&(this.st=void 0!==this.it?`{${this.it.map((t=>t.f)).join(",")}}`:`${this.rt}`),this.st}static ot(){return O.useGlobalEncodingBuffer?(BufferFormat.ht||(this.ht=new BufferWriter(O.encodingBufferMaxSize)),this.ht):new BufferWriter(O.encodingBufferInitialSize)}encodeInto(t,r){return r.subarray(0,this.encodeIntoLength(t,r))}encodeIntoLength(t,r){var e,i;this.tt&&(t=this.ft(t));const n=null!==(i=null===(e=this.ut)||void 0===e?void 0:e.q(r))&&void 0!==i?i:new BufferWriter(r);this.ut=void 0;try{return this.ct(t,n),n.R}finally{this.ut=n}}encode(t,r){return this.dt||(this.dt=BufferFormat.ot()),this.dt.R=0,this.tt&&(t=this.ft(t)),this.ct(t,this.dt),(null!=r?r:O.safe)?this.dt.L():this.dt.G()}decodeInto(t,r){return this.lt(t,r)}decode(t,r){return this.lt(t,r)}setTransforms(t){if(this.tt=!0,"function"==typeof t||Array.isArray(t)&&"function"==typeof t[0])this.$t=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set transforms for field '${r}'`);e.wt.setTransforms(t[r])}return this}setValidation(t){if(this.tt=!0,"function"==typeof t)this.yt=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set validation function for field '${r}'`);e.wt.setValidation(t[r])}return this}lt(t,r){var e,i;const n=void 0===this.header?0:2,s=null!==(i=null===(e=this.bt)||void 0===e?void 0:e.q(t,n))&&void 0!==i?i:new BufferReader(t,n);this.bt=void 0;try{return this.vt(s,r)}finally{this.bt=s}}ct(t,r){if(void 0!==this.nt&&r.l(this.nt),void 0!==this.rt){const e=this.yt||this.$t?this.ft(t):t;return H[this.rt](e,r)}if("object"!=typeof t||!t)throw new TypeError("expected object type");const e=this.it;for(let i=0;i`v.${t}=this.${this.It.name}(${r},s,v.${t})`)).join(";");return`let v=o??{};${t};return v;`}It(t,r,e){const i=this.it[t];if(!i.Ft||M.p(r))return i.At?this.Mt(i.wt,r,e):i.wt.vt(r,e)}gt(){return void 0!==this.rt?this.tt?t=>this.Et(k[this.rt](t)):k[this.rt]:new Function("s","o",this.Ut())}Tt(t,r,e){if(!Array.isArray(t))throw new TypeError(`expected array, instead got: ${t}`);l.h(t.length,r);for(let i=0;inew BufferParser,exports.defineFormat=function defineFormat(t,r){return null!==t&&"object"==typeof t?new BufferFormat(t):new BufferFormat(r,t)},exports.f16round=function f16round(t){return h(o(t))},exports.mask=mask,exports.optional=function optional(t){return new MaybeType(t)},exports.peekHeader=peekHeader,exports.peekHeaderStr=peekHeaderStr,exports.scalround=function scalround(t){return $fromscal8($toscal8(t))},exports.setTinybufConfig=t=>{O=Object.assign(Object.assign({},O),t)},exports.unmask=unmask,exports.uscalround=function uscalround(t){return $fromuscal8($touscal8(t))}; //# sourceMappingURL=index.cjs.map diff --git a/dist/index.cjs.map b/dist/index.cjs.map index 91627c3..9cc6256 100644 --- a/dist/index.cjs.map +++ b/dist/index.cjs.map @@ -1 +1 @@ -{"version":3,"file":"index.cjs","sources":["../src/core/lib/errors.ts","../src/core/lib/hashCode.ts","../src/core/lib/peek.ts","../src/core/BufferParser.ts","../src/core/lib/math.ts","../src/core/lib/scalar.ts","../src/core/Type.ts","../src/core/lib/bitmask.ts","../src/core/lib/utf8.ts","../src/core/lib/float16.ts","../src/core/lib/bfloat16.ts","../src/core/lib/coders.ts","../src/core/config.ts","../src/core/lib/BufferWriter.ts","../src/core/lib/BufferReader.ts","../src/core/BufferFormat.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unified-signatures */\n\nexport class TinybufError extends Error {}\n","/**\n * DJB2 hash algorithm (modified for 16-bit uints).\n *\n * DJB2 is a simple and widely used non-cryptographic\n * hash function created by Daniel J. Bernstein.\n *\n * @returns 16-bit unsigned integer\n */\nexport function $hashCode(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return hash & 0xFFFF; // Ensure the result is a Uint16\n}\n\n/**\n * Returns an unsigned 16-bit integer hashcode for some string.\n * Prefers 2 character string.\n *\n * @returns A UInt16 between 0 and 65535 (inclusive).\n */\nexport function $strToHashCode(str: string): number {\n if (str.length !== 2) return $hashCode(str);\n return str.charCodeAt(0) * 256 + str.charCodeAt(1);\n}\n\n/**\n * Convert a UInt16 hashcode to a 2-byte string.\n */\nexport function $hashCodeToStr(hashCode: number): string {\n return String.fromCharCode(Math.floor(hashCode / 256)) + String.fromCharCode(hashCode % 256);\n}\n","import { $hashCodeToStr } from \"./hashCode\";\n\n\n/**\n * Read the header bytes of a buffer as a number.\n *\n * @throws {RangeError} if buffer size < 2\n */\nexport function peekHeader(b: ArrayBuffer | ArrayBufferView): number {\n if (b.byteLength < 2) {\n throw new RangeError(\"buffer length < 2\");\n }\n\n if (b instanceof Uint8Array) return (b[0] << 8) | b[1];\n if (b instanceof DataView) return b.getUint16(0, false);\n\n const u8 = ArrayBuffer.isView(b) ? new Uint8Array(b.buffer, b.byteOffset, 2) : new Uint8Array(b, 0, 2);\n\n return (u8[0] << 8) | u8[1];\n}\n\n/**\n * Read the header bytes of a buffer as a string.\n *\n * @throws {RangeError} if buffer length < 2\n */\nexport function peekHeaderStr(b: ArrayBuffer | ArrayBufferView): string {\n return $hashCodeToStr(peekHeader(b));\n}\n","import { BufferFormat } from \"./BufferFormat\";\nimport { EncoderDefinition, DecodedType } from \"./Type\";\nimport { TinybufError } from \"./lib/errors\";\nimport { $hashCodeToStr, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader } from \"./lib/peek\";\n\ntype AnyFormat = BufferFormat;\ntype Uint16FormatHeader = number;\n\n/**\n * Small utility for registering and processing format handlers.\n *\n * @example\n * const myHandler = bufferParser()\n * .on(FormatA, aData => {})\n * .on(FormatB, bData => {});\n *\n * myHandler.processBuffer(bytes);\n */\nexport const bufferParser = (): BufferParser => new BufferParser();\n\nexport class BufferParser {\n /** @internal */\n private _$formats = new Map any, decodeInPlace: boolean]>();\n private _$data = new Map(); // used when decoding in-place\n\n /**\n * Decode an array buffer and trigger the relevant data handler.\n *\n * When passed an ArrayBufferView, accesses the underlying 'buffer' instance directly.\n *\n * @throws {TinybufError} if fails to decode, or no handler is registered\n */\n public processBuffer(b: ArrayBuffer | ArrayBufferView): void {\n let f: any, data: any, cb: (data: any) => any, r: boolean;\n\n try {\n const header = peekHeader(b);\n\n if (!this._$formats.has(header)) {\n throw new TinybufError(`Unknown format: ${header} '${$hashCodeToStr(header)}')`);\n }\n\n [f, cb, r] = this._$formats.get(header);\n if (r) data = this._$data.get(header) ?? {};\n data = f.decode(b, data);\n if (r) this._$data.set(header, data);\n }\n catch (e) {\n const err = new TinybufError(`Failed to decode: ${e}`);\n err.stack = e.stack;\n\n throw err;\n }\n\n cb(data);\n }\n\n /**\n * Register a format handler.\n */\n public on>(\n format: BufferFormat,\n callback: (data: TDecodedType) => any,\n {\n decodeInPlace = false,\n } = {},\n ): this {\n if (format.header == null) {\n throw new TinybufError(\"Format requires header\");\n }\n\n const header = typeof format.header === \"string\" ? $strToHashCode(format.header) : format.header;\n\n if (this._$formats.has(header) && this._$formats.get(header)?.[0] !== format) {\n throw new TinybufError(`Format header collision: ${format.header}`);\n }\n\n this._$formats.set(header, [format, callback, decodeInPlace]);\n\n return this;\n }\n\n /** Register a format (or formats) that are recognized. */\n public ignore(...format: AnyFormat[]): this {\n format.forEach(f => this.on(f, () => {}));\n return this;\n }\n\n /** Clears all registered formats and handlers. */\n public clear(): void {\n this._$formats.clear();\n this._$data.clear();\n }\n}\n","export const $floor = Math.floor,\n $ceil = Math.ceil;\n\n/** Clamp a number to a range. */\nexport const $clamp = (value: number, min: number, max: number): number =>\n value > max ? max : value < min ? min : value;\n\n/** Round toward zero */\nexport const $roundTowardZero = (x: number): number => x < 0 ? $ceil(x) : $floor(x);\n\n/** Round away zero */\nexport const $roundAwayFromZero = (x: number): number =>\n x < 0 ? $floor(x) : $ceil(x);\n","import { $clamp, $roundTowardZero, $roundAwayFromZero } from \"./math\";\n\n/**\n * Quantize a number to an 8-bit scalar between 0.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function uscalround(x: number): number {\n return $fromuscal8($touscal8(x));\n}\n\n/**\n * Quantize a number to an 8-bit signed scalar between -1.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function scalround(x: number): number {\n return $fromscal8($toscal8(x));\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $touscal8(x: number): number {\n return $clamp(127 + $roundTowardZero(x * 254 - 127), 0, 254);\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $toscal8(x: number): number {\n return $clamp($roundTowardZero(x * 127), -127, 127) + 127;\n}\n\n/** @returns An unsigned scalar between 0.0 and 1.0. */\nexport function $fromuscal8(x: number): number {\n // Make symmetric: (0.5 + round((uint8 - 127) / 254 * 100)) / 100\n return $clamp(($roundAwayFromZero((x - 127) * 0.3937007874015748) + 50) * 0.01, 0, 1);\n}\n\n/** @returns A signed scalar between -1.0 and 1.0. */\nexport function $fromscal8(x: number): number {\n // Make symmetric: round((uint8 - 127) / 127 * 100) / 100\n return $clamp($roundAwayFromZero((x - 127) * 0.787401574803149) * 0.01, -1, 1);\n}\n","/**\n * Field types for defining encoding formats.\n *\n * @see [Types](https://github.com/reececomo/tinybuf/blob/main/docs/types.md)\n */\nexport const Type = {\n /**\n * Unsigned integer (1 - 8 bytes).\n * - 0 → 127 = 1 byte\n * - 128 → 16,384 = 2 bytes\n * - 16,385 → 536,870,911 = 4 bytes\n * - 536,870,912 → `Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n UInt: \"uint\",\n\n /** Unsigned 8-bit integer (between 0 and 255, 1 byte). */\n UInt8: \"u8\",\n\n /** Unsigned 16-bit integer (between 0 and 65,535, 2 bytes). */\n UInt16: \"u16\",\n\n /** Unsigned 32-bit integer (between 0 and 4,294,967,295, 4 bytes). */\n UInt32: \"u32\",\n\n /**\n * Signed integer (1 - 8 bytes).\n * - 0 → ±64 = 1 byte\n * - ±65 → ±8,192 = 2 bytes\n * - ±8,193 → ±268,435,456 = 4 bytes\n * - ±268,435,457 → ±`Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n Int: \"int\",\n\n /** Signed 1 byte integer (between -127 and 127). */\n Int8: \"i8\",\n\n /** Signed 2 byte integer (between -32,767 and 32,767). */\n Int16: \"i16\",\n\n /** Signed 4 byte integer (between -2,147,483,647 and 2,147,483,647). */\n Int32: \"i32\",\n\n /** Default JavaScript `number` type. Floating-point number (64-bit, double precision, 8 bytes). */\n Float64: \"f64\",\n\n /** Floating-point number (32-bit, single precision, 4 bytes). */\n Float32: \"f32\",\n\n /**\n * Floating-point number (16-bit in FP16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision; maximum range: ±65,504.\n */\n Float16: \"f16\",\n\n /**\n * Floating-point number (16-bit in BF16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision.\n */\n BFloat16: \"b16\",\n\n /** A signed 2-decimal scalar between -1.00 and 1.00 (1 byte). */\n Scalar8: \"sc\",\n\n /** An unsigned 2-decimal scalar between 0.00 and 1.00 (1 byte). */\n UScalar8: \"usc\",\n\n /**\n * Boolean value (1 byte).\n * @see {Bools} for packing multiple booleans into a single byte.\n */\n Bool: \"bl\",\n\n /** Any array of booleans (1 bit overhead, encoded as UInt). */\n Bools: \"bls\",\n\n /** Any ArrayBuffer or ArrayBufferView (e.g. Uint8Array) value (encoded as 1 x UInt for byte length + buffer bytes). */\n Buffer: \"buf\",\n\n /** A UTF-8 string (encoded as 1 x UInt for UTF-8 byte length + UTF-8 bytes). */\n String: \"str\",\n\n /** Any JSON data (encodes as UTF-8). */\n JSON: \"jsn\",\n\n /** JavaScript RegExp object. */\n RegExp: \"re\",\n\n /**\n * JavaScript Date object.\n *\n * Encoded as an 8 byte (64-bit) integer UTC timestamp from as the number\n * of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).\n *\n * @see {Date}\n */\n Date: \"dt\",\n} as const;\n\nexport type TypeLiteral = typeof Type[keyof typeof Type];\nexport const ValidTypes = Object.values(Type);\n\n/**\n * Mappings for the value types.\n */\nexport type ValueTypes = {\n [Type.Int]: number;\n [Type.Int8]: number;\n [Type.Int16]: number;\n [Type.Int32]: number;\n [Type.UInt]: number;\n [Type.UInt8]: number;\n [Type.UInt16]: number;\n [Type.UInt32]: number;\n [Type.Float64]: number;\n [Type.Float32]: number;\n [Type.Float16]: number;\n [Type.BFloat16]: number;\n [Type.Scalar8]: number;\n [Type.UScalar8]: number;\n [Type.Bool]: boolean;\n [Type.Bools]: boolean[];\n [Type.Buffer]: Uint8Array | ArrayBuffer | ArrayBufferView;\n [Type.String]: string;\n [Type.JSON]: any;\n [Type.RegExp]: RegExp;\n [Type.Date]: Date;\n};\n\n/** https://www.totaltypescript.com/concepts/the-prettify-helper */\ntype Pretty = T extends ArrayBuffer | ArrayBufferView | Date | RegExp | Uint8Array ? T\n : T extends Array ? Array>\n : T extends object ? {[K in keyof T]: Pretty} & unknown : T;\n\n/** @throws any error too */\nexport type ValidationFn = (x: T) => undefined | boolean | Error;\nexport type TransformFn = (x: T) => T;\nexport type Transforms = TransformFn | [preEncode: TransformFn] | [preEncode: TransformFn | undefined, postDecode: TransformFn | undefined];\n\n/**\n * A wrapper around any Type definition that declares it as optional.\n */\nexport class MaybeType {\n public constructor(public type: T) {}\n}\n\n/**\n * Wrap any definition as optional.\n */\nexport function optional(t: T): MaybeType {\n return new MaybeType(t);\n}\n\n/**\n * A definition for an object binary encoder.\n */\nexport type EncoderDefinition = {\n [key: string]: FieldDefinition | MaybeType;\n};\n\n/**\n * Definition for an object-field binary encoder.\n */\nexport type FieldDefinition = keyof ValueTypes | [keyof ValueTypes] | EncoderDefinition | [EncoderDefinition] | MaybeType;\n\n/**\n * The resulting type of the decoded data, based on the encoder definition.\n */\ntype RawDecodedType = {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? never : EKey]: EncoderType[EKey] extends keyof ValueTypes\n ? ValueTypes[EncoderType[EKey]]\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Array\n : EncoderType[EKey] extends EncoderDefinition\n ? RawDecodedType\n : EncoderType[EKey] extends [EncoderDefinition]\n ? Array>\n : never;\n} & {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? EKey : never]?: EncoderType[EKey] extends MaybeType\n ? ValueTypes[OptionalValue] | undefined\n : EncoderType[EKey] extends MaybeType\n ? Array | undefined\n : EncoderType[EKey] extends MaybeType\n ? RawDecodedType | undefined\n : never;\n};\n\nexport type DecodedType = Pretty>;\n\nexport type TransformConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? Transforms\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Transforms\n : EncoderType[EKey] extends EncoderDefinition\n ? TransformConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? TransformConfig\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? TransformConfig | undefined\n : never;\n};\n\nexport type ValidationConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? ValidationFn\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? ValidationFn\n : EncoderType[EKey] extends EncoderDefinition\n ? ValidationConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? ValidationConfig\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationConfig | undefined\n : never;\n};\n","/**\n * Mask booleans to a uint32.\n *\n * @param x - A boolean array.\n * @param padBit - A bit to pad the mask (for variable length data).\n */\nexport const mask = (x: boolean[], padBit: 0 | 1 = 0b1): number => {\n return x.reduce((n, b: any) => (n << 1) | b, padBit);\n};\n\n/**\n * Unmask booleans from a uint32.\n *\n * @param x - A uint32 number.\n * @param l - number of booleans to expect (default: infer lenth from x where x is encoded with a pad bit)\n * or pass an existing boolean array to decode in-place.\n */\nexport const unmask = (x: number, l?: number | boolean[]): boolean[] => {\n const len = l === undefined ? 31 - Math.clz32(x) : Array.isArray(l) ? l.length : l;\n const val = Array.isArray(l) && l.length === len ? l : new Array(len);\n for (let i = 0; i < len; i++) val[i] = !!(x & (1 << (len - 1 - i)));\n return val;\n};\n","export const $utf8encode = (function () {\n const encoder = new TextEncoder();\n return (x?: string): Uint8Array => encoder.encode(x);\n})();\n\nexport const $utf8decode = (function () {\n const decoder = new TextDecoder(\"utf-8\");\n return (y: Uint8Array): string => decoder.decode(y);\n})();\n","/**\n * Returns the nearest half precision float representation of a number.\n * @param x A numeric expression.\n */\nexport function f16round(x: number): number {\n return $fromf16($tof16(x));\n}\n\n/**\n * Returns the nearest half precision float representation of a number as a 16-bit bitmask.\n */\nexport const $tof16 = (function() {\n const x = new Float32Array(1);\n const y = new Int32Array(x.buffer);\n\n return function (f: number) {\n x[0] = f;\n let i = y[0]; // 32-bit int\n let s = (i >> 16) & 0X8000; // sign\n let z = (i & 0X7FFFFFFF) + 0X1000 | 0;\n\n if (z >= 0X47800000) {\n if ((i & 0X7FFFFFFF) < 0X47800000) return s | 0X7BFF;\n if (z < 0X7F800000) return s | 0X7C00;\n return s | 0X7C00 | (i & 0X007FFFFF) >> 13;\n }\n if (z >= 0X38800000) return s | z - 0X38000000 >> 13;\n else if (z < 0X33000000) return s;\n z = (i & 0X7FFFFFFF) >> 23;\n return s | ((i & 0X7FFFFF | 0X800000)\n + (0X800000 >>> z - 102)\n >> 126 - z);\n };\n}());\n\n/**\n * Returns the nearest half precision float value for a 16-bit bitmask.\n */\nexport const $fromf16 = (function() {\n const z = Math.pow(2, -24); // subnormal constant\n const d = new Float32Array(32 + 1024);\n for (let e = 0; e < 32; e++) d[e] = Math.pow(2, e - 15); // biased exponents\n for (let m = 0; m < 1024; m++) d[m + 0x20] = 1 + m / 1024; // normalized offset mantissas\n\n return function (b: number): number {\n const s = (b & 32768) === 32768 ? -1 : 1; // sign: 1 bit\n const e = b & 31744; // exponent: 5 bits\n const m = b & 1023; // mantissa: 10 bits\n\n if (e === 0) return m === 0 ? s * 0 : s * z;\n if (e === 31744) return m === 0 ? s * Infinity : NaN;\n return d[e >> 10] * d[m + 0x20] * s;\n };\n}());\n","const i = new Uint32Array(1);\nconst f = new Float32Array(i.buffer);\n\n/**\n * Returns the nearest bfloat16 representation of a number.\n * @param x A numeric expression.\n */\nexport function bf16round(x: number): number {\n f[0] = x;\n i[0] = i[0] & 0xFFFF0000;\n return f[0];\n}\n\n/** Returns a 16-bit bfloat16 bitmask for a given float. */\nexport function $tobf16(x: number): number {\n f[0] = x;\n return i[0] >>> 16;\n}\n\n/** Returns the nearest value from a 16-bit bfloat16 bitmask. */\nexport function $frombf16(x: number): number {\n i[0] = x << 16;\n return f[0];\n}\n","import { BufferWriter } from \"./BufferWriter\";\nimport { BufferReader } from \"./BufferReader\";\nimport {\n $fromuscal8,\n $fromscal8,\n $touscal8,\n $toscal8\n} from \"./scalar\";\nimport { TypeLiteral, Type } from \"../Type\";\nimport { mask, unmask } from \"./bitmask\";\nimport { $utf8decode, $utf8encode } from \"./utf8\";\nimport { $floor } from \"./math\";\nimport { $fromf16, $tof16 } from \"./float16\";\nimport { $frombf16, $tobf16 } from \"./bfloat16\";\n\n// Pre-calculated constants\nconst MAX_VARUINT8 = 128,\n MAX_VARUINT16 = 16_384,\n MAX_VARUINT32 = 536_870_912,\n MAX_VARINT8 = 64,\n MAX_VARINT16 = 8_192,\n MAX_VARINT32 = 268_435_456,\n POW_32 = 0x100000000;\n\ntype WriterFn = (value: W, writer: BufferWriter) => void;\ntype ReaderFn = (reader: BufferReader, overwrite?: Partial) => R;\n\nexport interface BinaryTypeCoder {\n $write: WriterFn;\n $read: ReaderFn;\n}\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const uintCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value < 0) value = 0;\n if (value < MAX_VARUINT8) writer.$writeUint8(value);\n else if (value < MAX_VARUINT16) writer.$writeUint16(value + 0x8000);\n else if (value < MAX_VARUINT32) writer.$writeUint32(value + 0xc0000000);\n else if (value >= MAX_VARUINT32) {\n writer.$writeUint32($floor(value / POW_32) + 0xe0000000);\n writer.$writeUint32(value >>> 0);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 1 : 0);\n }\n },\n $read: (reader) => {\n const firstByte = reader.$peek();\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return firstByte;\n }\n else if (!(firstByte & 0x40)) {\n return reader.$readUint16() - 0x8000;\n }\n else if (!(firstByte & 0x20)) {\n return reader.$readUint32() - 0xc0000000;\n }\n\n return (reader.$readUint32() - 0xe0000000) * POW_32\n + reader.$readUint32();\n }\n};\n\nexport const uint8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value),\n $read: (reader) => reader.$readUint8(),\n};\n\nexport const uint16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16(value),\n $read: (reader) => reader.$readUint16(),\n};\n\nexport const uint32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint32(value),\n $read: (reader) => reader.$readUint32(),\n};\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const intCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value >= -MAX_VARINT8 && value < MAX_VARINT8) writer.$writeUint8(value & 0x7f);\n else if (value >= -MAX_VARINT16 && value < MAX_VARINT16) writer.$writeUint16((value & 0x3fff) + 0x8000);\n else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) + 0xc0000000);\n else if (value < -MAX_VARINT32 || value >= MAX_VARINT32) {\n // Split in two 32b uints\n writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) + 0xe0000000);\n writer.$writeUint32(value >>> 0);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 0x7f : 0);\n }\n },\n $read: (reader) => {\n let firstByte = reader.$peek(), i: number;\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return (firstByte & 0x40) ? (firstByte | 0xffffff80) : firstByte;\n }\n else if (!(firstByte & 0x40)) {\n i = reader.$readUint16() - 0x8000;\n return (i & 0x2000) ? (i | 0xffffc000) : i;\n }\n else if (!(firstByte & 0x20)) {\n i = reader.$readUint32() - 0xc0000000;\n return (i & 0x10000000) ? (i | 0xe0000000) : i;\n }\n else {\n i = reader.$readUint32() - 0xe0000000;\n i = (i & 0x10000000) ? (i | 0xe0000000) : i;\n return i * POW_32 + reader.$readUint32();\n }\n }\n};\n\nexport const int8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt8(value),\n $read: (reader) => reader.$readInt8(),\n};\n\nexport const int16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt16(value),\n $read: (reader) => reader.$readInt16(),\n};\n\nexport const int32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt32(value),\n $read: (reader) => reader.$readInt32(),\n};\n\nexport const bfloat16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tobf16(value)),\n $read: (reader) => $frombf16(reader.$readUint16()),\n};\n\nexport const float16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tof16(value)),\n $read: (reader) => $fromf16(reader.$readUint16()),\n};\n\nexport const float32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat32(value),\n $read: (reader) => reader.$readFloat32(),\n};\n\nexport const float64Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat64(value),\n $read: (reader) => reader.$readFloat64(),\n};\n\nexport const uscalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($touscal8(value)),\n $read: (reader) => $fromuscal8(reader.$readUint8()),\n};\n\nexport const scalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($toscal8(value)),\n $read: (reader) => $fromscal8(reader.$readUint8()),\n};\n\nexport const dateCoder: BinaryTypeCoder = {\n $write: (value, writer) => intCoder.$write(value.getTime(), writer),\n $read: (reader) => new Date(intCoder.$read(reader)),\n};\n\nexport const bufferCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n uintCoder.$write(value.byteLength, writer); // prefix length\n writer.$writeBytes(value);\n },\n $read: (reader) => reader.$readBytes(uintCoder.$read(reader)),\n};\n\nexport const stringCoder: BinaryTypeCoder = {\n $write: (value, writer) => bufferCoder.$write($utf8encode(value), writer),\n $read: (reader) => $utf8decode(bufferCoder.$read(reader)),\n};\n\nexport const boolCoder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value ? 1 : 0),\n $read: (reader) => reader.$readUint8() !== 0,\n};\n\nexport const boolsCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (value.length > 28) value = value.slice(0, 28); // drop additional\n uintCoder.$write(mask(value), writer);\n },\n $read: (reader, p) => unmask(uintCoder.$read(reader), p),\n};\n\nexport const jsonCoder: BinaryTypeCoder = {\n $write: (value, writer) => stringCoder.$write(JSON.stringify(value), writer),\n $read: (reader) => JSON.parse(stringCoder.$read(reader)),\n};\n\nexport const regexCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n writer.$writeUint8(mask([value.global, value.ignoreCase, value.multiline]));\n stringCoder.$write(value.source, writer);\n },\n $read: (reader) => {\n const [g, i, m] = unmask(reader.$readUint8());\n return new RegExp(stringCoder.$read(reader), (g ? \"g\" : \"\") + (i ? \"i\" : \"\") + (m ? \"m\" : \"\"));\n }\n};\n\nexport const writers: Record> = {\n [Type.UInt]: uintCoder.$write,\n [Type.UInt8]: uint8Coder.$write,\n [Type.UInt16]: uint16Coder.$write,\n [Type.UInt32]: uint32Coder.$write,\n [Type.Int]: intCoder.$write,\n [Type.Int8]: int8Coder.$write,\n [Type.Int16]: int16Coder.$write,\n [Type.Int32]: int32Coder.$write,\n [Type.Float64]: float64Coder.$write,\n [Type.Float32]: float32Coder.$write,\n [Type.Float16]: float16Coder.$write,\n [Type.BFloat16]: bfloat16Coder.$write,\n [Type.Scalar8]: scalar8Coder.$write,\n [Type.UScalar8]: uscalar8Coder.$write,\n [Type.Bool]: boolCoder.$write,\n [Type.Bools]: boolsCoder.$write,\n [Type.Buffer]: bufferCoder.$write,\n [Type.String]: stringCoder.$write,\n [Type.JSON]: jsonCoder.$write,\n [Type.RegExp]: regexCoder.$write,\n [Type.Date]: dateCoder.$write,\n};\n\nexport const readers: Record> = {\n [Type.UInt]: uintCoder.$read,\n [Type.UInt8]: uint8Coder.$read,\n [Type.UInt16]: uint16Coder.$read,\n [Type.UInt32]: uint32Coder.$read,\n [Type.Int]: intCoder.$read,\n [Type.Int8]: int8Coder.$read,\n [Type.Int16]: int16Coder.$read,\n [Type.Int32]: int32Coder.$read,\n [Type.Float64]: float64Coder.$read,\n [Type.Float32]: float32Coder.$read,\n [Type.Float16]: float16Coder.$read,\n [Type.BFloat16]: bfloat16Coder.$read,\n [Type.Scalar8]: scalar8Coder.$read,\n [Type.UScalar8]: uscalar8Coder.$read,\n [Type.Bool]: boolCoder.$read,\n [Type.Bools]: boolsCoder.$read,\n [Type.Buffer]: bufferCoder.$read,\n [Type.String]: stringCoder.$read,\n [Type.JSON]: jsonCoder.$read,\n [Type.RegExp]: regexCoder.$read,\n [Type.Date]: dateCoder.$read,\n};\n","/** Default maximum transmission unit in networking */\nconst MTU = 1500;\n\n/** Set Tinybuf global config */\nexport const setTinybufConfig = (c: Partial): void => {\n cfg = { ...cfg, ...c };\n};\n\nexport type TinybufConfig = {\n /**\n * (default: false)\n *\n * This sets the default value for `preserveBytes` on\n * `encode(data, preserveBytes?)`.\n *\n * By default, `encode()` returns its encoded bytes as a `Uint8Array`\n * view of the bytes in the shared encoding buffer.\n *\n * This is suitable for synchronous use (e.g. high-performance applications)\n * as it avoids slow and expensive memory allocation and fragmentation on\n * each call to `encode()`.\n *\n * However, susbsequent calls are destructive to the underlying bytes, so\n * for asynchronous uses (e.g. Promises, Workers, long-lived storage), set\n * `preserveBytes` to `true`.\n */\n safe: boolean,\n\n /**\n * (default: true)\n * By default, format encoders share a global encoding buffer for performance\n * and memory management reasons.\n *\n * When set to false, each format is allocated an individual encoding buffer.\n *\n * Enable to maximise performance and memory re-use, just be cautious of\n * possible race conditions.\n */\n useGlobalEncodingBuffer: boolean,\n\n /**\n * (default: 1500)\n * The maximum bytes that can be allocated to an encoding buffer.\n *\n * Default is 1500 bytes, the standard \"Maximum Transmission Unit\".\n */\n encodingBufferMaxSize: number,\n\n /**\n * (default: 256)\n * Initial bytes to allocate for an encoding buffer.\n */\n encodingBufferInitialSize: number,\n\n /**\n * (default: 256)\n * Additional bytes to allocated when dynamically increasing the size of an encoding buffer.\n */\n encodingBufferIncrement: number,\n};\n\n/** @internal */\nexport let cfg: TinybufConfig = {\n safe: false,\n useGlobalEncodingBuffer: true,\n encodingBufferMaxSize: MTU,\n encodingBufferInitialSize: 256,\n encodingBufferIncrement: 256,\n};\n","import { cfg } from \"../config\";\nimport { TinybufError } from \"./errors\";\n\n/**\n * Wraps a buffer with a write head pointer.\n *\n * @internal\n */\nexport class BufferWriter {\n public $byteLength: number = 0;\n private _$dataView: DataView;\n private _$bytes: Uint8Array;\n private _$base: number;\n private _$writeHead: number = 0;\n private _$resizable: boolean;\n\n public constructor($0: number | Uint8Array) {\n this._$resizable = typeof $0 === \"number\";\n let b = $0 instanceof Uint8Array ? $0 : new Uint8Array($0);\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$dataView = new DataView(b.buffer);\n }\n\n /** Retarget the writer to a fixed-size byte array, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array): this {\n if (this._$dataView.buffer !== b.buffer) {\n this._$dataView = new DataView(b.buffer);\n }\n\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$resizable = false;\n this._$writeHead = 0;\n this.$byteLength = 0;\n\n return this;\n }\n\n public $viewBytes(): Uint8Array {\n return this._$bytes.subarray(0, this.$byteLength);\n }\n\n public $copyBytes(): Uint8Array {\n const buf = new Uint8Array(this.$byteLength);\n buf.set(this.$viewBytes());\n return buf;\n }\n\n // ----- Writers: -----\n\n public $writeInt8(value: number): void {\n this._$pre(1).setInt8(this._$writeHead, value);\n }\n\n public $writeInt16(value: number): void {\n this._$pre(2).setInt16(this._$writeHead, value, true);\n }\n\n public $writeInt32(value: number): void {\n this._$pre(4).setInt32(this._$writeHead, value, true);\n }\n\n public $writeUint8(value: number): void {\n this._$pre(1).setUint8(this._$writeHead, value);\n }\n\n public $writeUint16(value: number): void {\n this._$pre(2).setUint16(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeUint32(value: number): void {\n this._$pre(4).setUint32(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeFloat32(value: number): void {\n this._$pre(4).setFloat32(this._$writeHead, value, true);\n }\n\n public $writeFloat64(value: number): void {\n this._$pre(8).setFloat64(this._$writeHead, value, true);\n }\n\n public $writeBytes(b: Uint8Array | ArrayBuffer | ArrayBufferView): void {\n // allocate bytes first\n this._$pre(b.byteLength);\n\n this._$bytes.set(\n b instanceof Uint8Array\n ? b\n : ArrayBuffer.isView(b)\n ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n : new Uint8Array(b),\n this._$writeHead - this._$base\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Pre-allocate some bytes on the dataview, moving the write head into\n * position.\n *\n * @throws TinybufError\n */\n private _$pre(bytes: number): DataView {\n if (this.$byteLength + bytes > this._$bytes.byteLength) {\n this._$malloc(bytes);\n }\n\n this._$writeHead = this._$base + this.$byteLength;\n this.$byteLength += bytes;\n\n return this._$dataView;\n }\n\n /**\n * @throws TinybufError\n */\n private _$malloc(bytes: number): void {\n if (!this._$resizable) {\n throw new TinybufError(\"exceeded buffer length: \" + this._$bytes.byteLength);\n }\n\n const currentBytes = this._$bytes.byteLength;\n const minNewBytes = this.$byteLength + bytes - currentBytes;\n const availableBytes = cfg.encodingBufferMaxSize - currentBytes;\n\n if (minNewBytes > availableBytes) {\n throw new TinybufError(\"exceeded encodingBufferMaxSize: \" + cfg.encodingBufferMaxSize);\n }\n\n const increment = cfg.encodingBufferIncrement;\n const newBytes = Math.ceil(minNewBytes / increment) * increment;\n const newSize = currentBytes + Math.min(newBytes, availableBytes);\n const buf = new Uint8Array(newSize);\n\n // copy bytes\n buf.set(this._$bytes);\n\n // update refs\n this._$dataView = new DataView(buf.buffer);\n this._$bytes = buf;\n this._$base = 0;\n }\n}\n","/**\n * Wraps a buffer with a read head pointer.\n *\n * @internal\n */\nexport class BufferReader {\n public i: number;\n private _$dataView!: DataView;\n private _$base!: number;\n private _$byteLength!: number;\n\n public constructor(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number) {\n this.$reset(b, headerBytes);\n }\n\n /** Retarget the reader to a new buffer, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number): this {\n const isView = ArrayBuffer.isView(b);\n const buffer = isView ? b.buffer : b;\n const offset = isView ? b.byteOffset : 0;\n let dv = this._$dataView;\n\n if (\n dv === undefined\n || dv.buffer !== buffer\n || offset < dv.byteOffset\n || offset + b.byteLength > dv.byteOffset + dv.byteLength\n ) {\n dv = this._$dataView = b instanceof DataView ? b : new DataView(buffer);\n }\n\n this._$base = offset - dv.byteOffset;\n this._$byteLength = b.byteLength;\n this.i = headerBytes ?? 0; // internal offset (header)\n\n return this;\n }\n\n /** Read the next byte, without moving the read head pointer. */\n public $peek(): number {\n if (this.i >= this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n return this._$dataView.getUint8(this._$base + this.i);\n }\n\n /** Skip the next byte without reading it. */\n public $skip(): void {\n this.i++;\n }\n\n // ----- Readers: -----\n\n public $readUint8(): number {\n return this._$dataView.getUint8(this._$at(1));\n }\n\n public $readUint16(): number {\n return this._$dataView.getUint16(this._$at(2)); // big-endian\n }\n\n public $readUint32(): number {\n return this._$dataView.getUint32(this._$at(4)); // big-endian\n }\n\n public $readInt8(): number {\n return this._$dataView.getInt8(this._$at(1));\n }\n\n public $readInt16(): number {\n return this._$dataView.getInt16(this._$at(2), true); // little-endian\n }\n\n public $readInt32(): number {\n return this._$dataView.getInt32(this._$at(4), true); // little-endian\n }\n\n public $readFloat32(): number {\n return this._$dataView.getFloat32(this._$at(4), true); // little-endian\n }\n\n public $readFloat64(): number {\n return this._$dataView.getFloat64(this._$at(8), true); // little-endian\n }\n\n /** @throws RangeError if exceeds length */\n public $readBytes(bytes: number): Uint8Array {\n return new Uint8Array(\n this._$dataView.buffer,\n this._$dataView.byteOffset + this._$at(bytes),\n bytes\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Advance the read head, returning the DataView offset to read from.\n *\n * @throws RangeError if exceeds length\n */\n private _$at(bytes: number): number {\n const i = this.i;\n\n if (i + bytes > this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n this.i = i + bytes;\n\n return this._$base + i;\n }\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { writers, readers } from \"./lib/coders\";\nimport * as coders from \"./lib/coders\";\nimport { $hashCode, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader, peekHeaderStr } from \"./lib/peek\";\nimport { BufferWriter } from \"./lib/BufferWriter\";\nimport { BufferReader } from \"./lib/BufferReader\";\nimport {\n DecodedType,\n EncoderDefinition,\n FieldDefinition,\n TransformConfig,\n ValidationConfig,\n MaybeType,\n Transforms,\n TypeLiteral,\n ValidationFn,\n ValidTypes,\n} from \"./Type\";\nimport { cfg } from \"./config\";\n\nexport type FormatHeader = string | number;\n\n/**\n * Utility to get the decoded type of a buffer format\n * @example type Format = Decoded\n */\nexport type Decoded = TBufferFormat extends BufferFormat\n ? DecodedType\n : never;\n\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(def: T): BufferFormat;\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(h: HeaderType | null, def: T): BufferFormat;\nexport function defineFormat(a?: HeaderType | T, b?: T): BufferFormat {\n return a !== null && typeof a === \"object\"\n ? new BufferFormat(a as T)\n : new BufferFormat(b as T, a as HeaderType);\n}\n\nfunction isValidHeader(h: FormatHeader): boolean {\n if (typeof h === \"number\") return Number.isInteger(h) && h >= 0 && h <= 65_535;\n if (typeof h === \"string\") return new TextEncoder().encode(h).byteLength === 2;\n return false;\n}\n\n/**\n * BufferFormat is a utility class for encoding and decoding binary data based\n * on a provided encoding format.\n *\n * @see {header}\n * @see {encode(data)}\n * @see {decode(binary)}\n */\nexport class BufferFormat {\n /** @internal */\n private static _$globalWriter?: BufferWriter;\n\n /**\n * A unique identifier encoded as the first 2 bytes (or `undefined` if headerless).\n *\n * @see {peekHeader(...)}\n * @see {peekHeaderStr(...)}\n */\n public header!: HeaderType;\n\n /** @internal */\n private _$header!: number; // always uint16 vesion\n /** @internal */\n private _$type!: TypeLiteral;\n /** @internal */\n private _$fields!: Field[];\n /** @internal */\n private _$fieldsMap!: Map;\n\n /** @internal */\n private _$format?: string;\n /** @internal */\n private _$transforms?: Transforms | undefined;\n /** @internal */\n private _$validate?: ValidationFn | undefined;\n /** @internal */\n private _$hasValidationOrTransforms = false;\n /** @internal */\n private _$writer?: BufferWriter;\n /** @internal */\n private _$intoWriter?: BufferWriter;\n /** @internal */\n private _$reader?: BufferReader;\n\n public constructor(\n def: EncoderType,\n header?: HeaderType | null,\n ) {\n // set definition\n if (typeof def === \"string\" && ValidTypes.includes(def)) {\n this._$type = def;\n }\n else if (def instanceof MaybeType) {\n throw new TypeError(\"Format cannot be optional\");\n }\n else if (def instanceof Object) {\n this._$type = undefined; // object\n this._$fieldsMap = new Map();\n this._$fields = Object.keys(def).map((name) => {\n const f = new Field(name, def[name]);\n this._$fieldsMap.set(name, f); // also set map entry\n return f;\n });\n\n // set headers\n if (header === undefined) {\n this.header = $hashCode(this.f) as HeaderType; // automatic\n this._$header = this.header as number;\n }\n else if (header === null) {\n this.header = undefined; // headerless\n this._$header = undefined;\n }\n else if (isValidHeader(header)) {\n this.header = header; // manual\n this._$header = typeof header === \"number\" ? header : $strToHashCode(header);\n }\n else {\n throw new TypeError(\"Header must be 2-byte string, uint16, or null.\");\n }\n }\n else {\n throw new TypeError(\"Format must be object or Type\");\n }\n }\n\n // ----- Static methods: -----\n\n /**\n * Read the header of a buffer as a number.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeader = peekHeader;\n\n /**\n * Read the header of a buffer as a string.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeaderStr = peekHeaderStr;\n\n // ----- Accessors: -----\n\n /**\n * @example \"{uint8,str[]?}\"\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private get f(): string {\n if (this._$format === undefined) {\n this._$format = this._$fields !== undefined\n ? `{${this._$fields.map(v => v.f).join(\",\")}}`\n : `${this._$type}`;\n }\n\n return this._$format;\n }\n\n /** @internal */\n private static _$initWriter(): BufferWriter {\n if (cfg.useGlobalEncodingBuffer) {\n if (!BufferFormat._$globalWriter) {\n this._$globalWriter = new BufferWriter(cfg.encodingBufferMaxSize);\n }\n\n return this._$globalWriter;\n }\n\n return new BufferWriter(cfg.encodingBufferInitialSize);\n }\n\n /**\n * Encode an object into an existing byte array.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n */\n public encodeInto>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): Uint8Array {\n return bytes.subarray(0, this.encodeIntoLength(data, bytes));\n }\n\n /**\n * Encode an object into an existing byte array, without allocating a view.\n *\n * @returns the number of bytes written to the start of `bytes`\n * @throws if fails to encode value to schema, or `bytes` is too small\n */\n public encodeIntoLength>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): number {\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n const writer = this._$intoWriter?.$reset(bytes) ?? new BufferWriter(bytes);\n this._$intoWriter = undefined;\n\n try {\n this._$write(data, writer);\n\n return writer.$byteLength;\n }\n finally {\n this._$intoWriter = writer;\n }\n }\n\n /**\n * Encode an object to bytes.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n *\n * @param data - data to encode\n * @param preserveBytes - (default: `setTinybufConfig().safe`) When set to true, copies encoded\n * bytes to a new buffer. When set to false, returns an unsafe view of bytes but prevents\n * unnnecessary memory allocation and fragmentation.\n *\n * @returns a copy of encoded bytes\n * @throws if fails to encode value to schema\n */\n public encode>(\n data: TDecodedType,\n preserveBytes?: boolean,\n ): Uint8Array {\n if (!this._$writer) {\n // lazy init\n this._$writer = BufferFormat._$initWriter();\n }\n\n // reset\n this._$writer.$byteLength = 0;\n\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n this._$write(data, this._$writer);\n\n return (preserveBytes ?? cfg.safe)\n ? this._$writer.$copyBytes()\n : this._$writer.$viewBytes();\n }\n\n /**\n * Decode binary data into an existing object instance.\n * @throws if fails to decode bytes to schema.\n */\n public decodeInto>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial,\n ): TDecodedType {\n return this._$decode(bytes, obj);\n }\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer\n ): TDecodedType;\n /**\n * @deprecated use decodeInto() instead\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto: Partial,\n ): TDecodedType;\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto?: Partial | undefined,\n ): TDecodedType {\n return this._$decode(bytes, decodeInto);\n }\n\n /**\n * Set additional transform functions to apply before encoding and after decoding.\n */\n public setTransforms(transforms: TransformConfig | Transforms): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof transforms === \"function\" || (Array.isArray(transforms) && typeof transforms[0] === \"function\")) {\n this._$transforms = transforms;\n }\n else {\n for (const name of Object.keys(transforms)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set transforms for field '${name}'`);\n }\n\n // Set validation for object.\n field.$coder.setTransforms(transforms[name]);\n }\n }\n\n return this;\n }\n\n /**\n * Set additional validation rules which are applied on encode() and decode().\n *\n * - Validation functions should throw an error, return an error, or return boolean false.\n * - Anything else is treated as successfully passing validation.\n */\n public setValidation(validations: ValidationConfig | ValidationFn): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof validations === \"function\") {\n this._$validate = validations;\n }\n else {\n for (const name of Object.keys(validations)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set validation function for field '${name}'`);\n }\n\n field.$coder.setValidation(validations[name]);\n }\n }\n\n return this;\n }\n\n // ----- Implementation: -----\n\n /** @internal */\n private _$decode(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial | undefined,\n ): TDecodedType {\n const headerBytes = this.header === undefined ? 0 : 2;\n\n const reader = this._$reader?.$reset(bytes, headerBytes) ?? new BufferReader(bytes, headerBytes);\n this._$reader = undefined;\n\n try {\n return this._$read(reader, obj);\n }\n finally {\n this._$reader = reader;\n }\n }\n\n /**\n * @param value\n * @param bw\n * @throws if the value is invalid\n *\n * @internal\n */\n private _$write(value: any, bw: BufferWriter): void {\n // write header\n if (this._$header !== undefined) bw.$writeUint16(this._$header);\n\n // write scalar\n if (this._$type !== undefined) {\n const safeValue = (this._$validate || this._$transforms) ? this._$preprocess(value) : value;\n\n return writers[this._$type](safeValue, bw);\n }\n\n // check for object type\n if (typeof value !== \"object\" || !value) {\n throw new TypeError(\"expected object type\");\n }\n\n // write each field\n for (const field of this._$fields) {\n const subValue = value[field.$name];\n\n if (field.$isOptional) {\n if (subValue === undefined || subValue === null) {\n coders.boolCoder.$write(false, bw);\n continue; // skip\n }\n else {\n coders.boolCoder.$write(true, bw);\n }\n }\n else if (subValue == null) {\n throw new Error(`missing required value: ${field.$name}`);\n }\n\n if (field.$isArray) {\n // array\n this._$writeArray(subValue, bw, field.$coder);\n continue;\n }\n\n // scalar/object field\n field.$coder._$write(subValue, bw);\n }\n }\n\n /**\n * pre-process: validation and/or transforms\n * @internal\n */\n private _$preprocess>(data: T): T {\n if (this._$validate) this._$processValidation(data);\n\n if (typeof this._$transforms === \"function\") {\n return this._$transforms(data);\n }\n else if (Array.isArray(this._$transforms) && typeof this._$transforms[0] === \"function\") {\n return this._$transforms[0](data);\n }\n\n return data;\n }\n\n /**\n * post-process: validation and/or transforms\n * @internal\n */\n private _$postprocess>(data: T): T {\n if (Array.isArray(this._$transforms) && typeof this._$transforms[1] === \"function\") {\n data = this._$transforms[1](data);\n }\n\n if (this._$validate) this._$processValidation(data);\n\n return data;\n }\n\n private _$processValidation(data: any): void {\n if (!this._$validate) return;\n const res = this._$validate(data);\n if (res instanceof Error) throw res;\n if (res === false) throw new Error(\"failed validation\");\n }\n\n /**\n * This function will be executed only the first time\n * After that, we'll compile the read routine and add it directly to the instance\n * @param state\n * @returns\n * @throws if fails\n *\n * @internal\n */\n private _$read>(state: BufferReader, obj?: Partial): TDecodedType {\n // This function will be executed only the first time to compile the read routine.\n // After that, we'll compile the read routine and add it directly to the instance\n\n // Update the read method implementation.\n this._$read = this._$compileFormatReadFn();\n\n return this._$read(state, obj);\n }\n\n /**\n * Generate read function code for this coder.\n *\n * @example\n * let v=o??{};\n * v.prop1=this._$readField(0,s,o);\n * v.prop2=this._$readField(1,s,o);\n * return v\n *\n * @internal\n */\n private _$makeObjectReadFnBody(): string {\n const fieldsStr: string = this._$fields\n .map(({ $name: n }, i) => `v.${n}=this.${this._$readField.name}(${i},s,v.${n})`)\n .join(\";\");\n\n return `let v=o??{};${fieldsStr};return v;`;\n }\n\n /**\n * Read an individual field.\n * @internal\n */\n private _$readField(fieldIndex: number, state: BufferReader, obj?: any): any {\n const field = this._$fields[fieldIndex];\n\n if (field.$isOptional && !coders.boolCoder.$read(state)) {\n return undefined;\n }\n\n if (field.$isArray) {\n return this._$readArray(field.$coder, state, obj);\n }\n\n return field.$coder._$read(state, obj);\n }\n\n /**\n * Compile the decode() method for this object.\n *\n * @internal\n */\n private _$compileFormatReadFn>(): (state: BufferReader, obj: Partial | undefined) => TDecodedType {\n if (this._$type !== undefined) {\n // scalar type\n return this._$hasValidationOrTransforms\n ? (s) => this._$postprocess(readers[this._$type](s))\n : readers[this._$type];\n }\n\n // object type\n return new Function(\"s\", \"o\", this._$makeObjectReadFnBody()) as any;\n }\n\n /**\n * @internal\n */\n private _$writeArray(value: any[], bw: BufferWriter, type: BufferFormat): void {\n if (!Array.isArray(value)) {\n throw new TypeError(`expected array, instead got: ${value}`);\n }\n\n coders.uintCoder.$write(value.length, bw);\n for (let i = 0; i < value.length; i++) {\n type._$write(value[i], bw);\n }\n }\n\n /**\n * @throws if invalid data\n * @internal\n */\n private _$readArray(type: BufferFormat, state: any, obj?: Array): Array {\n const len = coders.uintCoder.$read(state);\n const arr = Array.isArray(obj) ? obj : new Array(len);\n if (arr.length !== len) arr.length = len;\n for (let j = 0; j < arr.length; j++) {\n arr[j] = type._$read(state, obj?.[j]);\n }\n return arr;\n }\n}\n\n/**\n * Parses and represents an object field.\n *\n * @internal\n */\nclass Field {\n public $name: string;\n public $coder: BufferFormat;\n public $isOptional: boolean;\n public $isArray: boolean;\n\n private _$formatString?: string;\n\n public constructor(name: string, rawType: FieldDefinition) {\n this.$isOptional = rawType instanceof MaybeType;\n let type = rawType instanceof MaybeType ? rawType.type : rawType;\n\n this.$name = name;\n\n if (Array.isArray(type)) {\n if (type.length !== 1) {\n throw new TypeError(\"Array type must contain exactly one format\");\n }\n\n type = type[0];\n this.$isArray = true;\n }\n else {\n this.$isArray = false;\n }\n\n this.$coder = new BufferFormat(type, null);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public get f(): string {\n if (this._$formatString === undefined) {\n this._$formatString = `${(this.$coder as any).f}${this.$isArray ? \"[]\" : \"\"}${this.$isOptional ? \"?\" : \"\"}`;\n }\n\n return this._$formatString;\n }\n}\n"],"names":["TinybufError","Error","$hashCode","str","hash","i","length","charCodeAt","$strToHashCode","$hashCodeToStr","hashCode","String","fromCharCode","Math","floor","peekHeader","b","byteLength","RangeError","Uint8Array","DataView","getUint16","u8","ArrayBuffer","isView","buffer","byteOffset","peekHeaderStr","BufferParser","constructor","this","_$formats","Map","_$data","processBuffer","f","data","cb","r","header","has","get","_a","decode","set","e","err","stack","on","format","callback","decodeInPlace","ignore","forEach","clear","$floor","$ceil","ceil","$clamp","value","min","max","$roundTowardZero","x","$roundAwayFromZero","$touscal8","$toscal8","$fromuscal8","$fromscal8","Type","UInt","UInt8","UInt16","UInt32","Int","Int8","Int16","Int32","Float64","Float32","Float16","BFloat16","Scalar8","UScalar8","Bool","Bools","Buffer","JSON","RegExp","Date","ValidTypes","Object","values","MaybeType","type","mask","padBit","reduce","n","unmask","l","len","undefined","clz32","Array","isArray","val","$utf8encode","encoder","TextEncoder","encode","$utf8decode","decoder","TextDecoder","y","$tof16","Float32Array","Int32Array","s","z","$fromf16","pow","d","m","Infinity","NaN","Uint32Array","MAX_VARUINT32","MAX_VARINT32","POW_32","uintCoder","$write","writer","Number","$writeUint8","$writeUint16","$writeUint32","$read","reader","firstByte","$peek","$readUint32","$readUint16","$skip","uint8Coder","$readUint8","uint16Coder","uint32Coder","intCoder","int8Coder","$writeInt8","$readInt8","int16Coder","$writeInt16","$readInt16","int32Coder","$writeInt32","$readInt32","bfloat16Coder","$tobf16","$frombf16","float16Coder","float32Coder","$writeFloat32","$readFloat32","float64Coder","$writeFloat64","$readFloat64","uscalar8Coder","scalar8Coder","dateCoder","getTime","bufferCoder","$writeBytes","$readBytes","stringCoder","boolCoder","boolsCoder","slice","p","jsonCoder","stringify","parse","regexCoder","global","ignoreCase","multiline","source","g","writers","readers","cfg","safe","useGlobalEncodingBuffer","encodingBufferMaxSize","encodingBufferInitialSize","encodingBufferIncrement","BufferWriter","$0","$byteLength","_$writeHead","_$resizable","_$bytes","_$base","_$dataView","$reset","$viewBytes","subarray","$copyBytes","buf","_$pre","setInt8","setInt16","setInt32","setUint8","setUint16","setUint32","setFloat32","setFloat64","bytes","_$malloc","currentBytes","minNewBytes","availableBytes","increment","newBytes","newSize","BufferReader","headerBytes","offset","dv","_$byteLength","getUint8","_$at","getUint32","getInt8","getInt16","getInt32","getFloat32","getFloat64","BufferFormat","def","_$hasValidationOrTransforms","includes","_$type","TypeError","_$fieldsMap","_$fields","keys","map","name","Field","_$header","isValidHeader","h","isInteger","_$format","v","join","_$initWriter","_$globalWriter","encodeInto","encodeIntoLength","_$preprocess","_b","_$intoWriter","_$write","preserveBytes","_$writer","decodeInto","obj","_$decode","setTransforms","transforms","_$transforms","field","$coder","setValidation","validations","_$validate","_$reader","_$read","bw","safeValue","subValue","$name","$isOptional","coders.boolCoder","$isArray","_$writeArray","_$processValidation","_$postprocess","res","state","_$compileFormatReadFn","_$makeObjectReadFnBody","fieldsStr","_$readField","fieldIndex","_$readArray","Function","coders.uintCoder","arr","j","rawType","_$formatString","bf16round","defineFormat","a","f16round","optional","t","scalround","c","assign","uscalround"],"mappings":"AAEM,MAAOA,qBAAqBC,OCM5B,SAAUC,UAAUC,GACxB,IAAIC,EAAO,KACX,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAC9BD,EAAe,GAAPA,EAAaD,EAAII,WAAWF,GAEtC,OAAc,MAAPD,CACT,CAQM,SAAUI,eAAeL,GAC7B,OAAmB,IAAfA,EAAIG,OAAqBJ,UAAUC,GACZ,IAApBA,EAAII,WAAW,GAAWJ,EAAII,WAAW,EAClD,CAKM,SAAUE,eAAeC,GAC7B,OAAOC,OAAOC,aAAaC,KAAKC,MAAMJ,EAAW,MAAQC,OAAOC,aAAaF,EAAW,IAC1F,CCxBM,SAAUK,WAAWC,GACzB,GAAIA,EAAEC,WAAa,EACjB,MAAM,IAAIC,WAAW,qBAGvB,GAAIF,aAAaG,WAAY,OAAQH,EAAE,IAAM,EAAKA,EAAE,GACpD,GAAIA,aAAaI,SAAU,OAAOJ,EAAEK,UAAU,GAAG,GAEjD,MAAMC,EAAKC,YAAYC,OAAOR,GAAK,IAAIG,WAAWH,EAAES,OAAQT,EAAEU,WAAY,GAAK,IAAIP,WAAWH,EAAG,EAAG,GAEpG,OAAQM,EAAG,IAAM,EAAKA,EAAG,EAC3B,CAOM,SAAUK,cAAcX,GAC5B,OAAOP,eAAeM,WAAWC,GACnC,OCPaY,aAAb,WAAAC,GAEUC,KAAAC,EAAY,IAAIC,IAChBF,KAAAG,EAAS,IAAID,GAsEtB,CA7DQ,aAAAE,CAAclB,SACnB,IAAImB,EAAQC,EAAWC,EAAwBC,EAE/C,IACE,MAAMC,EAASxB,WAAWC,GAE1B,IAAKc,KAAKC,EAAUS,IAAID,GACtB,MAAM,IAAIvC,aAAa,mBAAm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/errors.ts","../src/core/lib/hashCode.ts","../src/core/lib/peek.ts","../src/core/BufferParser.ts","../src/core/lib/math.ts","../src/core/lib/scalar.ts","../src/core/Type.ts","../src/core/lib/bitmask.ts","../src/core/lib/utf8.ts","../src/core/lib/float16.ts","../src/core/lib/bfloat16.ts","../src/core/lib/coders.ts","../src/core/config.ts","../src/core/lib/BufferWriter.ts","../src/core/lib/BufferReader.ts","../src/core/BufferFormat.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unified-signatures */\n\nexport class TinybufError extends Error {}\n","/**\n * DJB2 hash algorithm (modified for 16-bit uints).\n *\n * DJB2 is a simple and widely used non-cryptographic\n * hash function created by Daniel J. Bernstein.\n *\n * @returns 16-bit unsigned integer\n */\nexport function $hashCode(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return hash & 0xFFFF; // Ensure the result is a Uint16\n}\n\n/**\n * Returns an unsigned 16-bit integer hashcode for some string.\n * Prefers 2 character string.\n *\n * @returns A UInt16 between 0 and 65535 (inclusive).\n */\nexport function $strToHashCode(str: string): number {\n if (str.length !== 2) return $hashCode(str);\n return str.charCodeAt(0) * 256 + str.charCodeAt(1);\n}\n\n/**\n * Convert a UInt16 hashcode to a 2-byte string.\n */\nexport function $hashCodeToStr(hashCode: number): string {\n return String.fromCharCode(Math.floor(hashCode / 256)) + String.fromCharCode(hashCode % 256);\n}\n","import { $hashCodeToStr } from \"./hashCode\";\n\n\n/**\n * Read the header bytes of a buffer as a number.\n *\n * @throws {RangeError} if buffer size < 2\n */\nexport function peekHeader(b: ArrayBuffer | ArrayBufferView): number {\n if (b.byteLength < 2) {\n throw new RangeError(\"buffer length < 2\");\n }\n\n if (b instanceof Uint8Array) return (b[0] << 8) | b[1];\n if (b instanceof DataView) return b.getUint16(0, false);\n\n const u8 = ArrayBuffer.isView(b) ? new Uint8Array(b.buffer, b.byteOffset, 2) : new Uint8Array(b, 0, 2);\n\n return (u8[0] << 8) | u8[1];\n}\n\n/**\n * Read the header bytes of a buffer as a string.\n *\n * @throws {RangeError} if buffer length < 2\n */\nexport function peekHeaderStr(b: ArrayBuffer | ArrayBufferView): string {\n return $hashCodeToStr(peekHeader(b));\n}\n","import { BufferFormat } from \"./BufferFormat\";\nimport { EncoderDefinition, DecodedType } from \"./Type\";\nimport { TinybufError } from \"./lib/errors\";\nimport { $hashCodeToStr, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader } from \"./lib/peek\";\n\ntype AnyFormat = BufferFormat;\ntype Uint16FormatHeader = number;\n\n/**\n * Small utility for registering and processing format handlers.\n *\n * @example\n * const myHandler = bufferParser()\n * .on(FormatA, aData => {})\n * .on(FormatB, bData => {});\n *\n * myHandler.processBuffer(bytes);\n */\nexport const bufferParser = (): BufferParser => new BufferParser();\n\nexport class BufferParser {\n /** @internal */\n private _$formats = new Map any, decodeInPlace: boolean]>();\n private _$data = new Map(); // used when decoding in-place\n\n /**\n * Decode an array buffer and trigger the relevant data handler.\n *\n * When passed an ArrayBufferView, accesses the underlying 'buffer' instance directly.\n *\n * @throws {TinybufError} if fails to decode, or no handler is registered\n */\n public processBuffer(b: ArrayBuffer | ArrayBufferView): void {\n let f: any, data: any, cb: (data: any) => any, r: boolean;\n\n try {\n const header = peekHeader(b);\n\n if (!this._$formats.has(header)) {\n throw new TinybufError(`Unknown format: ${header} '${$hashCodeToStr(header)}')`);\n }\n\n [f, cb, r] = this._$formats.get(header);\n if (r) data = this._$data.get(header) ?? {};\n data = f.decode(b, data);\n if (r) this._$data.set(header, data);\n }\n catch (e) {\n const err = new TinybufError(`Failed to decode: ${e}`);\n err.stack = e.stack;\n\n throw err;\n }\n\n cb(data);\n }\n\n /**\n * Register a format handler.\n */\n public on>(\n format: BufferFormat,\n callback: (data: TDecodedType) => any,\n {\n decodeInPlace = false,\n } = {},\n ): this {\n if (format.header == null) {\n throw new TinybufError(\"Format requires header\");\n }\n\n const header = typeof format.header === \"string\" ? $strToHashCode(format.header) : format.header;\n\n if (this._$formats.has(header) && this._$formats.get(header)?.[0] !== format) {\n throw new TinybufError(`Format header collision: ${format.header}`);\n }\n\n this._$formats.set(header, [format, callback, decodeInPlace]);\n\n return this;\n }\n\n /** Register a format (or formats) that are recognized. */\n public ignore(...format: AnyFormat[]): this {\n format.forEach(f => this.on(f, () => {}));\n return this;\n }\n\n /** Clears all registered formats and handlers. */\n public clear(): void {\n this._$formats.clear();\n this._$data.clear();\n }\n}\n","export const $floor = Math.floor,\n $ceil = Math.ceil;\n\n/** Clamp a number to a range. */\nexport const $clamp = (value: number, min: number, max: number): number =>\n value > max ? max : value < min ? min : value;\n\n/** Round toward zero */\nexport const $roundTowardZero = (x: number): number => x < 0 ? $ceil(x) : $floor(x);\n\n/** Round away zero */\nexport const $roundAwayFromZero = (x: number): number =>\n x < 0 ? $floor(x) : $ceil(x);\n","import { $clamp, $roundTowardZero, $roundAwayFromZero } from \"./math\";\n\n/**\n * Quantize a number to an 8-bit scalar between 0.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function uscalround(x: number): number {\n return $fromuscal8($touscal8(x));\n}\n\n/**\n * Quantize a number to an 8-bit signed scalar between -1.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function scalround(x: number): number {\n return $fromscal8($toscal8(x));\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $touscal8(x: number): number {\n return $clamp(127 + $roundTowardZero(x * 254 - 127), 0, 254);\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $toscal8(x: number): number {\n return $clamp($roundTowardZero(x * 127), -127, 127) + 127;\n}\n\n/** @returns An unsigned scalar between 0.0 and 1.0. */\nexport function $fromuscal8(x: number): number {\n // Make symmetric: (0.5 + round((uint8 - 127) / 254 * 100)) / 100\n return $clamp(($roundAwayFromZero((x - 127) * 0.3937007874015748) + 50) * 0.01, 0, 1);\n}\n\n/** @returns A signed scalar between -1.0 and 1.0. */\nexport function $fromscal8(x: number): number {\n // Make symmetric: round((uint8 - 127) / 127 * 100) / 100\n return $clamp($roundAwayFromZero((x - 127) * 0.787401574803149) * 0.01, -1, 1);\n}\n","/**\n * Field types for defining encoding formats.\n *\n * @see [Types](https://github.com/reececomo/tinybuf/blob/main/docs/types.md)\n */\nexport const Type = {\n /**\n * Unsigned integer (1 - 8 bytes).\n * - 0 → 127 = 1 byte\n * - 128 → 16,384 = 2 bytes\n * - 16,385 → 536,870,911 = 4 bytes\n * - 536,870,912 → `Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n UInt: \"uint\",\n\n /** Unsigned 8-bit integer (between 0 and 255, 1 byte). */\n UInt8: \"u8\",\n\n /** Unsigned 16-bit integer (between 0 and 65,535, 2 bytes). */\n UInt16: \"u16\",\n\n /** Unsigned 32-bit integer (between 0 and 4,294,967,295, 4 bytes). */\n UInt32: \"u32\",\n\n /**\n * Signed integer (1 - 8 bytes).\n * - 0 → ±64 = 1 byte\n * - ±65 → ±8,192 = 2 bytes\n * - ±8,193 → ±268,435,456 = 4 bytes\n * - ±268,435,457 → ±`Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n Int: \"int\",\n\n /** Signed 1 byte integer (between -127 and 127). */\n Int8: \"i8\",\n\n /** Signed 2 byte integer (between -32,767 and 32,767). */\n Int16: \"i16\",\n\n /** Signed 4 byte integer (between -2,147,483,647 and 2,147,483,647). */\n Int32: \"i32\",\n\n /** Default JavaScript `number` type. Floating-point number (64-bit, double precision, 8 bytes). */\n Float64: \"f64\",\n\n /** Floating-point number (32-bit, single precision, 4 bytes). */\n Float32: \"f32\",\n\n /**\n * Floating-point number (16-bit in FP16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision; maximum range: ±65,504.\n */\n Float16: \"f16\",\n\n /**\n * Floating-point number (16-bit in BF16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision.\n */\n BFloat16: \"b16\",\n\n /** A signed 2-decimal scalar between -1.00 and 1.00 (1 byte). */\n Scalar8: \"sc\",\n\n /** An unsigned 2-decimal scalar between 0.00 and 1.00 (1 byte). */\n UScalar8: \"usc\",\n\n /**\n * Boolean value (1 byte).\n * @see {Bools} for packing multiple booleans into a single byte.\n */\n Bool: \"bl\",\n\n /** Any array of booleans (1 bit overhead, encoded as UInt). */\n Bools: \"bls\",\n\n /** Any ArrayBuffer or ArrayBufferView (e.g. Uint8Array) value (encoded as 1 x UInt for byte length + buffer bytes). */\n Buffer: \"buf\",\n\n /** A UTF-8 string (encoded as 1 x UInt for UTF-8 byte length + UTF-8 bytes). */\n String: \"str\",\n\n /** Any JSON data (encodes as UTF-8). */\n JSON: \"jsn\",\n\n /** JavaScript RegExp object. */\n RegExp: \"re\",\n\n /**\n * JavaScript Date object.\n *\n * Encoded as an 8 byte (64-bit) integer UTC timestamp from as the number\n * of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).\n *\n * @see {Date}\n */\n Date: \"dt\",\n} as const;\n\nexport type TypeLiteral = typeof Type[keyof typeof Type];\nexport const ValidTypes = Object.values(Type);\n\n/**\n * Mappings for the value types.\n */\nexport type ValueTypes = {\n [Type.Int]: number;\n [Type.Int8]: number;\n [Type.Int16]: number;\n [Type.Int32]: number;\n [Type.UInt]: number;\n [Type.UInt8]: number;\n [Type.UInt16]: number;\n [Type.UInt32]: number;\n [Type.Float64]: number;\n [Type.Float32]: number;\n [Type.Float16]: number;\n [Type.BFloat16]: number;\n [Type.Scalar8]: number;\n [Type.UScalar8]: number;\n [Type.Bool]: boolean;\n [Type.Bools]: boolean[];\n [Type.Buffer]: Uint8Array | ArrayBuffer | ArrayBufferView;\n [Type.String]: string;\n [Type.JSON]: any;\n [Type.RegExp]: RegExp;\n [Type.Date]: Date;\n};\n\n/** https://www.totaltypescript.com/concepts/the-prettify-helper */\ntype Pretty = T extends ArrayBuffer | ArrayBufferView | Date | RegExp | Uint8Array ? T\n : T extends Array ? Array>\n : T extends object ? {[K in keyof T]: Pretty} & unknown : T;\n\n/** @throws any error too */\nexport type ValidationFn = (x: T) => undefined | boolean | Error;\nexport type TransformFn = (x: T) => T;\nexport type Transforms = TransformFn | [preEncode: TransformFn] | [preEncode: TransformFn | undefined, postDecode: TransformFn | undefined];\n\n/**\n * A wrapper around any Type definition that declares it as optional.\n */\nexport class MaybeType {\n public constructor(public type: T) {}\n}\n\n/**\n * Wrap any definition as optional.\n */\nexport function optional(t: T): MaybeType {\n return new MaybeType(t);\n}\n\n/**\n * A definition for an object binary encoder.\n */\nexport type EncoderDefinition = {\n [key: string]: FieldDefinition | MaybeType;\n};\n\n/**\n * Definition for an object-field binary encoder.\n */\nexport type FieldDefinition = keyof ValueTypes | [keyof ValueTypes] | EncoderDefinition | [EncoderDefinition] | MaybeType;\n\n/**\n * The resulting type of the decoded data, based on the encoder definition.\n */\ntype RawDecodedType = {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? never : EKey]: EncoderType[EKey] extends keyof ValueTypes\n ? ValueTypes[EncoderType[EKey]]\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Array\n : EncoderType[EKey] extends EncoderDefinition\n ? RawDecodedType\n : EncoderType[EKey] extends [EncoderDefinition]\n ? Array>\n : never;\n} & {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? EKey : never]?: EncoderType[EKey] extends MaybeType\n ? ValueTypes[OptionalValue] | undefined\n : EncoderType[EKey] extends MaybeType\n ? Array | undefined\n : EncoderType[EKey] extends MaybeType\n ? RawDecodedType | undefined\n : never;\n};\n\nexport type DecodedType = Pretty>;\n\nexport type TransformConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? Transforms\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Transforms\n : EncoderType[EKey] extends EncoderDefinition\n ? TransformConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? TransformConfig\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? TransformConfig | undefined\n : never;\n};\n\nexport type ValidationConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? ValidationFn\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? ValidationFn\n : EncoderType[EKey] extends EncoderDefinition\n ? ValidationConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? ValidationConfig\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationConfig | undefined\n : never;\n};\n","/**\n * Mask booleans to a uint32.\n *\n * @param x - A boolean array.\n * @param padBit - A bit to pad the mask (for variable length data).\n */\nexport const mask = (x: boolean[], padBit: 0 | 1 = 0b1): number => {\n return x.reduce((n, b: any) => (n << 1) | b, padBit);\n};\n\n/**\n * Unmask booleans from a uint32.\n *\n * @param x - A uint32 number.\n * @param l - number of booleans to expect (default: infer lenth from x where x is encoded with a pad bit)\n * or pass an existing boolean array to decode in-place.\n */\nexport const unmask = (x: number, l?: number | boolean[]): boolean[] => {\n const len = l === undefined ? 31 - Math.clz32(x) : Array.isArray(l) ? l.length : l;\n const val = Array.isArray(l) && l.length === len ? l : new Array(len);\n for (let i = 0; i < len; i++) val[i] = !!(x & (1 << (len - 1 - i)));\n return val;\n};\n","export const $utf8encode = (function () {\n const encoder = new TextEncoder();\n return (x?: string): Uint8Array => encoder.encode(x);\n})();\n\nexport const $utf8decode = (function () {\n const decoder = new TextDecoder(\"utf-8\");\n return (y: Uint8Array): string => decoder.decode(y);\n})();\n","/**\n * Returns the nearest half precision float representation of a number.\n * @param x A numeric expression.\n */\nexport function f16round(x: number): number {\n return $fromf16($tof16(x));\n}\n\n/**\n * Returns the nearest half precision float representation of a number as a 16-bit bitmask.\n */\nexport const $tof16 = (function() {\n const x = new Float32Array(1);\n const y = new Int32Array(x.buffer);\n\n return function (f: number) {\n x[0] = f;\n let i = y[0]; // 32-bit int\n let s = (i >> 16) & 0X8000; // sign\n let z = (i & 0X7FFFFFFF) + 0X1000 | 0;\n\n if (z >= 0X47800000) {\n if ((i & 0X7FFFFFFF) < 0X47800000) return s | 0X7BFF;\n if (z < 0X7F800000) return s | 0X7C00;\n return s | 0X7C00 | (i & 0X007FFFFF) >> 13;\n }\n if (z >= 0X38800000) return s | z - 0X38000000 >> 13;\n else if (z < 0X33000000) return s;\n z = (i & 0X7FFFFFFF) >> 23;\n return s | ((i & 0X7FFFFF | 0X800000)\n + (0X800000 >>> z - 102)\n >> 126 - z);\n };\n}());\n\n/**\n * Returns the nearest half precision float value for a 16-bit bitmask.\n */\nexport const $fromf16 = (function() {\n const z = Math.pow(2, -24); // subnormal constant\n const d = new Float32Array(32 + 1024);\n for (let e = 0; e < 32; e++) d[e] = Math.pow(2, e - 15); // biased exponents\n for (let m = 0; m < 1024; m++) d[m + 0x20] = 1 + m / 1024; // normalized offset mantissas\n\n return function (b: number): number {\n const s = (b & 32768) === 32768 ? -1 : 1; // sign: 1 bit\n const e = b & 31744; // exponent: 5 bits\n const m = b & 1023; // mantissa: 10 bits\n\n if (e === 0) return m === 0 ? s * 0 : s * z;\n if (e === 31744) return m === 0 ? s * Infinity : NaN;\n return d[e >> 10] * d[m + 0x20] * s;\n };\n}());\n","const i = new Uint32Array(1);\nconst f = new Float32Array(i.buffer);\n\n/**\n * Returns the nearest bfloat16 representation of a number.\n * @param x A numeric expression.\n */\nexport function bf16round(x: number): number {\n f[0] = x;\n i[0] = i[0] & 0xFFFF0000;\n return f[0];\n}\n\n/** Returns a 16-bit bfloat16 bitmask for a given float. */\nexport function $tobf16(x: number): number {\n f[0] = x;\n return i[0] >>> 16;\n}\n\n/** Returns the nearest value from a 16-bit bfloat16 bitmask. */\nexport function $frombf16(x: number): number {\n i[0] = x << 16;\n return f[0];\n}\n","import { BufferWriter } from \"./BufferWriter\";\nimport { BufferReader } from \"./BufferReader\";\nimport {\n $fromuscal8,\n $fromscal8,\n $touscal8,\n $toscal8\n} from \"./scalar\";\nimport { TypeLiteral, Type } from \"../Type\";\nimport { mask, unmask } from \"./bitmask\";\nimport { $utf8decode, $utf8encode } from \"./utf8\";\nimport { $floor } from \"./math\";\nimport { $fromf16, $tof16 } from \"./float16\";\nimport { $frombf16, $tobf16 } from \"./bfloat16\";\n\n// Pre-calculated constants\nconst MAX_VARUINT8 = 128,\n MAX_VARUINT16 = 16_384,\n MAX_VARUINT32 = 536_870_912,\n MAX_VARINT8 = 64,\n MAX_VARINT16 = 8_192,\n MAX_VARINT32 = 268_435_456,\n POW_32 = 0x100000000;\n\ntype WriterFn = (value: W, writer: BufferWriter) => void;\ntype ReaderFn = (reader: BufferReader, overwrite?: Partial) => R;\n\nexport interface BinaryTypeCoder {\n $write: WriterFn;\n $read: ReaderFn;\n}\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const uintCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value < 0) value = 0;\n if (value < MAX_VARUINT8) writer.$writeUint8(value);\n else if (value < MAX_VARUINT16) writer.$writeUint16(value + 0x8000);\n else if (value < MAX_VARUINT32) writer.$writeUint32((value + 0xc0000000) | 0);\n else if (value >= MAX_VARUINT32) {\n writer.$writeUint32(($floor(value / POW_32) + 0xe0000000) | 0);\n writer.$writeUint16(value >>> 16);\n writer.$writeUint16(value & 0xffff);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 1 : 0);\n }\n },\n $read: (reader) => {\n const firstByte = reader.$peek();\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return firstByte;\n }\n else if (!(firstByte & 0x40)) {\n return reader.$readUint16() - 0x8000;\n }\n else if (!(firstByte & 0x20)) {\n return reader.$readUint32() - 0xc0000000;\n }\n\n return (reader.$readUint32() - 0xe0000000) * POW_32\n + reader.$readUint32();\n }\n};\n\nexport const uint8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value),\n $read: (reader) => reader.$readUint8(),\n};\n\nexport const uint16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16(value),\n $read: (reader) => reader.$readUint16(),\n};\n\nexport const uint32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint32(value),\n $read: (reader) => reader.$readUint32(),\n};\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const intCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value >= -MAX_VARINT8 && value < MAX_VARINT8) writer.$writeUint8(value & 0x7f);\n else if (value >= -MAX_VARINT16 && value < MAX_VARINT16) writer.$writeUint16((value & 0x3fff) + 0x8000);\n else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) | 0xc0000000);\n else if (value < -MAX_VARINT32 || value >= MAX_VARINT32) {\n // Split in two 32b uints\n writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) | 0xe0000000);\n writer.$writeUint16(value >>> 16);\n writer.$writeUint16(value & 0xffff);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 0x7f : 0);\n }\n },\n $read: (reader) => {\n let firstByte = reader.$peek(), i: number;\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return (firstByte & 0x40) ? (firstByte | 0xffffff80) : firstByte;\n }\n else if (!(firstByte & 0x40)) {\n i = reader.$readUint16() - 0x8000;\n return (i & 0x2000) ? (i | 0xffffc000) : i;\n }\n else if (!(firstByte & 0x20)) {\n i = reader.$readUint32() - 0xc0000000;\n return (i & 0x10000000) ? (i | 0xe0000000) : i;\n }\n else {\n i = reader.$readUint32() - 0xe0000000;\n i = (i & 0x10000000) ? (i | 0xe0000000) : i;\n return i * POW_32 + reader.$readUint32();\n }\n }\n};\n\nexport const int8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt8(value),\n $read: (reader) => reader.$readInt8(),\n};\n\nexport const int16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt16(value),\n $read: (reader) => reader.$readInt16(),\n};\n\nexport const int32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt32(value),\n $read: (reader) => reader.$readInt32(),\n};\n\nexport const bfloat16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tobf16(value)),\n $read: (reader) => $frombf16(reader.$readUint16()),\n};\n\nexport const float16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tof16(value)),\n $read: (reader) => $fromf16(reader.$readUint16()),\n};\n\nexport const float32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat32(value),\n $read: (reader) => reader.$readFloat32(),\n};\n\nexport const float64Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat64(value),\n $read: (reader) => reader.$readFloat64(),\n};\n\nexport const uscalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($touscal8(value)),\n $read: (reader) => $fromuscal8(reader.$readUint8()),\n};\n\nexport const scalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($toscal8(value)),\n $read: (reader) => $fromscal8(reader.$readUint8()),\n};\n\nexport const dateCoder: BinaryTypeCoder = {\n $write: (value, writer) => intCoder.$write(value.getTime(), writer),\n $read: (reader) => new Date(intCoder.$read(reader)),\n};\n\nexport const bufferCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n uintCoder.$write(value.byteLength, writer); // prefix length\n writer.$writeBytes(value);\n },\n $read: (reader) => reader.$readBytes(uintCoder.$read(reader)),\n};\n\nexport const stringCoder: BinaryTypeCoder = {\n $write: (value, writer) => bufferCoder.$write($utf8encode(value), writer),\n $read: (reader) => $utf8decode(bufferCoder.$read(reader)),\n};\n\nexport const boolCoder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value ? 1 : 0),\n $read: (reader) => reader.$readUint8() !== 0,\n};\n\nexport const boolsCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (value.length > 28) value = value.slice(0, 28); // drop additional\n uintCoder.$write(mask(value), writer);\n },\n $read: (reader, p) => unmask(uintCoder.$read(reader), p),\n};\n\nexport const jsonCoder: BinaryTypeCoder = {\n $write: (value, writer) => stringCoder.$write(JSON.stringify(value), writer),\n $read: (reader) => JSON.parse(stringCoder.$read(reader)),\n};\n\nexport const regexCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n writer.$writeUint8(mask([value.global, value.ignoreCase, value.multiline]));\n stringCoder.$write(value.source, writer);\n },\n $read: (reader) => {\n const [g, i, m] = unmask(reader.$readUint8());\n return new RegExp(stringCoder.$read(reader), (g ? \"g\" : \"\") + (i ? \"i\" : \"\") + (m ? \"m\" : \"\"));\n }\n};\n\nexport const writers: Record> = {\n [Type.UInt]: uintCoder.$write,\n [Type.UInt8]: uint8Coder.$write,\n [Type.UInt16]: uint16Coder.$write,\n [Type.UInt32]: uint32Coder.$write,\n [Type.Int]: intCoder.$write,\n [Type.Int8]: int8Coder.$write,\n [Type.Int16]: int16Coder.$write,\n [Type.Int32]: int32Coder.$write,\n [Type.Float64]: float64Coder.$write,\n [Type.Float32]: float32Coder.$write,\n [Type.Float16]: float16Coder.$write,\n [Type.BFloat16]: bfloat16Coder.$write,\n [Type.Scalar8]: scalar8Coder.$write,\n [Type.UScalar8]: uscalar8Coder.$write,\n [Type.Bool]: boolCoder.$write,\n [Type.Bools]: boolsCoder.$write,\n [Type.Buffer]: bufferCoder.$write,\n [Type.String]: stringCoder.$write,\n [Type.JSON]: jsonCoder.$write,\n [Type.RegExp]: regexCoder.$write,\n [Type.Date]: dateCoder.$write,\n};\n\nexport const readers: Record> = {\n [Type.UInt]: uintCoder.$read,\n [Type.UInt8]: uint8Coder.$read,\n [Type.UInt16]: uint16Coder.$read,\n [Type.UInt32]: uint32Coder.$read,\n [Type.Int]: intCoder.$read,\n [Type.Int8]: int8Coder.$read,\n [Type.Int16]: int16Coder.$read,\n [Type.Int32]: int32Coder.$read,\n [Type.Float64]: float64Coder.$read,\n [Type.Float32]: float32Coder.$read,\n [Type.Float16]: float16Coder.$read,\n [Type.BFloat16]: bfloat16Coder.$read,\n [Type.Scalar8]: scalar8Coder.$read,\n [Type.UScalar8]: uscalar8Coder.$read,\n [Type.Bool]: boolCoder.$read,\n [Type.Bools]: boolsCoder.$read,\n [Type.Buffer]: bufferCoder.$read,\n [Type.String]: stringCoder.$read,\n [Type.JSON]: jsonCoder.$read,\n [Type.RegExp]: regexCoder.$read,\n [Type.Date]: dateCoder.$read,\n};\n","/** Default maximum transmission unit in networking */\nconst MTU = 1500;\n\n/** Set Tinybuf global config */\nexport const setTinybufConfig = (c: Partial): void => {\n cfg = { ...cfg, ...c };\n};\n\nexport type TinybufConfig = {\n /**\n * (default: false)\n *\n * This sets the default value for `preserveBytes` on\n * `encode(data, preserveBytes?)`.\n *\n * By default, `encode()` returns its encoded bytes as a `Uint8Array`\n * view of the bytes in the shared encoding buffer.\n *\n * This is suitable for synchronous use (e.g. high-performance applications)\n * as it avoids slow and expensive memory allocation and fragmentation on\n * each call to `encode()`.\n *\n * However, susbsequent calls are destructive to the underlying bytes, so\n * for asynchronous uses (e.g. Promises, Workers, long-lived storage), set\n * `preserveBytes` to `true`.\n */\n safe: boolean,\n\n /**\n * (default: true)\n * By default, format encoders share a global encoding buffer for performance\n * and memory management reasons.\n *\n * When set to false, each format is allocated an individual encoding buffer.\n *\n * Enable to maximise performance and memory re-use, just be cautious of\n * possible race conditions.\n */\n useGlobalEncodingBuffer: boolean,\n\n /**\n * (default: 1500)\n * The maximum bytes that can be allocated to an encoding buffer.\n *\n * Default is 1500 bytes, the standard \"Maximum Transmission Unit\".\n */\n encodingBufferMaxSize: number,\n\n /**\n * (default: 256)\n * Initial bytes to allocate for an encoding buffer.\n */\n encodingBufferInitialSize: number,\n\n /**\n * (default: 256)\n * Additional bytes to allocated when dynamically increasing the size of an encoding buffer.\n */\n encodingBufferIncrement: number,\n};\n\n/** @internal */\nexport let cfg: TinybufConfig = {\n safe: false,\n useGlobalEncodingBuffer: true,\n encodingBufferMaxSize: MTU,\n encodingBufferInitialSize: 256,\n encodingBufferIncrement: 256,\n};\n","import { cfg } from \"../config\";\nimport { TinybufError } from \"./errors\";\n\n/**\n * Wraps a buffer with a write head pointer.\n *\n * @internal\n */\nexport class BufferWriter {\n public $byteLength: number = 0;\n private _$dataView: DataView;\n private _$bytes: Uint8Array;\n private _$base: number;\n private _$writeHead: number = 0;\n private _$resizable: boolean;\n\n public constructor($0: number | Uint8Array) {\n this._$resizable = typeof $0 === \"number\";\n let b = $0 instanceof Uint8Array ? $0 : new Uint8Array($0);\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$dataView = new DataView(b.buffer);\n }\n\n /** Retarget the writer to a fixed-size byte array, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array): this {\n if (this._$dataView.buffer !== b.buffer) {\n this._$dataView = new DataView(b.buffer);\n }\n\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$resizable = false;\n this._$writeHead = 0;\n this.$byteLength = 0;\n\n return this;\n }\n\n public $viewBytes(): Uint8Array {\n return this._$bytes.subarray(0, this.$byteLength);\n }\n\n public $copyBytes(): Uint8Array {\n const buf = new Uint8Array(this.$byteLength);\n buf.set(this.$viewBytes());\n return buf;\n }\n\n // ----- Writers: -----\n\n public $writeInt8(value: number): void {\n this._$pre(1).setInt8(this._$writeHead, value);\n }\n\n public $writeInt16(value: number): void {\n this._$pre(2).setInt16(this._$writeHead, value, true);\n }\n\n public $writeInt32(value: number): void {\n this._$pre(4).setInt32(this._$writeHead, value, true);\n }\n\n public $writeUint8(value: number): void {\n this._$pre(1).setUint8(this._$writeHead, value);\n }\n\n public $writeUint16(value: number): void {\n this._$pre(2).setUint16(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeUint32(value: number): void {\n this._$pre(4).setUint32(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeFloat32(value: number): void {\n this._$pre(4).setFloat32(this._$writeHead, value, true);\n }\n\n public $writeFloat64(value: number): void {\n this._$pre(8).setFloat64(this._$writeHead, value, true);\n }\n\n public $writeBytes(b: Uint8Array | ArrayBuffer | ArrayBufferView): void {\n // allocate bytes first\n this._$pre(b.byteLength);\n\n this._$bytes.set(\n b instanceof Uint8Array\n ? b\n : ArrayBuffer.isView(b)\n ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n : new Uint8Array(b),\n this._$writeHead - this._$base\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Pre-allocate some bytes on the dataview, moving the write head into\n * position.\n *\n * @throws TinybufError\n */\n private _$pre(bytes: number): DataView {\n if (this.$byteLength + bytes > this._$bytes.byteLength) {\n this._$malloc(bytes);\n }\n\n this._$writeHead = this._$base + this.$byteLength;\n this.$byteLength += bytes;\n\n return this._$dataView;\n }\n\n /**\n * @throws TinybufError\n */\n private _$malloc(bytes: number): void {\n if (!this._$resizable) {\n throw new TinybufError(\"exceeded buffer length: \" + this._$bytes.byteLength);\n }\n\n const currentBytes = this._$bytes.byteLength;\n const minNewBytes = this.$byteLength + bytes - currentBytes;\n const availableBytes = cfg.encodingBufferMaxSize - currentBytes;\n\n if (minNewBytes > availableBytes) {\n throw new TinybufError(\"exceeded encodingBufferMaxSize: \" + cfg.encodingBufferMaxSize);\n }\n\n const increment = cfg.encodingBufferIncrement;\n const newBytes = Math.ceil(minNewBytes / increment) * increment;\n const newSize = currentBytes + Math.min(newBytes, availableBytes);\n const buf = new Uint8Array(newSize);\n\n // copy bytes\n buf.set(this._$bytes);\n\n // update refs\n this._$dataView = new DataView(buf.buffer);\n this._$bytes = buf;\n this._$base = 0;\n }\n}\n","/**\n * Wraps a buffer with a read head pointer.\n *\n * @internal\n */\nexport class BufferReader {\n public i: number;\n private _$dataView!: DataView;\n private _$base!: number;\n private _$byteLength!: number;\n\n public constructor(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number) {\n this.$reset(b, headerBytes);\n }\n\n /** Retarget the reader to a new buffer, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number): this {\n const isView = ArrayBuffer.isView(b);\n const buffer = isView ? b.buffer : b;\n const offset = isView ? b.byteOffset : 0;\n let dv = this._$dataView;\n\n if (\n dv === undefined\n || dv.buffer !== buffer\n || offset < dv.byteOffset\n || offset + b.byteLength > dv.byteOffset + dv.byteLength\n ) {\n dv = this._$dataView = b instanceof DataView ? b : new DataView(buffer);\n }\n\n this._$base = offset - dv.byteOffset;\n this._$byteLength = b.byteLength;\n this.i = headerBytes ?? 0; // internal offset (header)\n\n return this;\n }\n\n /** Read the next byte, without moving the read head pointer. */\n public $peek(): number {\n if (this.i >= this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n return this._$dataView.getUint8(this._$base + this.i);\n }\n\n /** Skip the next byte without reading it. */\n public $skip(): void {\n this.i++;\n }\n\n // ----- Readers: -----\n\n public $readUint8(): number {\n return this._$dataView.getUint8(this._$at(1));\n }\n\n public $readUint16(): number {\n return this._$dataView.getUint16(this._$at(2)); // big-endian\n }\n\n public $readUint32(): number {\n return this._$dataView.getUint32(this._$at(4)); // big-endian\n }\n\n public $readInt8(): number {\n return this._$dataView.getInt8(this._$at(1));\n }\n\n public $readInt16(): number {\n return this._$dataView.getInt16(this._$at(2), true); // little-endian\n }\n\n public $readInt32(): number {\n return this._$dataView.getInt32(this._$at(4), true); // little-endian\n }\n\n public $readFloat32(): number {\n return this._$dataView.getFloat32(this._$at(4), true); // little-endian\n }\n\n public $readFloat64(): number {\n return this._$dataView.getFloat64(this._$at(8), true); // little-endian\n }\n\n /** @throws RangeError if exceeds length */\n public $readBytes(bytes: number): Uint8Array {\n return new Uint8Array(\n this._$dataView.buffer,\n this._$dataView.byteOffset + this._$at(bytes),\n bytes\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Advance the read head, returning the DataView offset to read from.\n *\n * @throws RangeError if exceeds length\n */\n private _$at(bytes: number): number {\n const i = this.i;\n\n if (i + bytes > this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n this.i = i + bytes;\n\n return this._$base + i;\n }\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { writers, readers } from \"./lib/coders\";\nimport * as coders from \"./lib/coders\";\nimport { $hashCode, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader, peekHeaderStr } from \"./lib/peek\";\nimport { BufferWriter } from \"./lib/BufferWriter\";\nimport { BufferReader } from \"./lib/BufferReader\";\nimport {\n DecodedType,\n EncoderDefinition,\n FieldDefinition,\n TransformConfig,\n ValidationConfig,\n MaybeType,\n Transforms,\n TypeLiteral,\n ValidationFn,\n ValidTypes,\n} from \"./Type\";\nimport { cfg } from \"./config\";\n\nexport type FormatHeader = string | number;\n\n/**\n * Utility to get the decoded type of a buffer format\n * @example type Format = Decoded\n */\nexport type Decoded = TBufferFormat extends BufferFormat\n ? DecodedType\n : never;\n\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(def: T): BufferFormat;\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(h: HeaderType | null, def: T): BufferFormat;\nexport function defineFormat(a?: HeaderType | T, b?: T): BufferFormat {\n return a !== null && typeof a === \"object\"\n ? new BufferFormat(a as T)\n : new BufferFormat(b as T, a as HeaderType);\n}\n\nfunction isValidHeader(h: FormatHeader): boolean {\n if (typeof h === \"number\") return Number.isInteger(h) && h >= 0 && h <= 65_535;\n if (typeof h === \"string\") return new TextEncoder().encode(h).byteLength === 2;\n return false;\n}\n\n/**\n * BufferFormat is a utility class for encoding and decoding binary data based\n * on a provided encoding format.\n *\n * @see {header}\n * @see {encode(data)}\n * @see {decode(binary)}\n */\nexport class BufferFormat {\n /** @internal */\n private static _$globalWriter?: BufferWriter;\n\n /**\n * A unique identifier encoded as the first 2 bytes (or `undefined` if headerless).\n *\n * @see {peekHeader(...)}\n * @see {peekHeaderStr(...)}\n */\n public header!: HeaderType;\n\n /** @internal */\n private _$header!: number; // always uint16 vesion\n /** @internal */\n private _$type!: TypeLiteral;\n /** @internal */\n private _$fields!: Field[];\n /** @internal */\n private _$fieldsMap!: Map;\n\n /** @internal */\n private _$format?: string;\n /** @internal */\n private _$transforms?: Transforms | undefined;\n /** @internal */\n private _$validate?: ValidationFn | undefined;\n /** @internal */\n private _$hasValidationOrTransforms = false;\n /** @internal */\n private _$writer?: BufferWriter;\n /** @internal */\n private _$intoWriter?: BufferWriter;\n /** @internal */\n private _$reader?: BufferReader;\n\n public constructor(\n def: EncoderType,\n header?: HeaderType | null,\n ) {\n // set definition\n if (typeof def === \"string\" && ValidTypes.includes(def)) {\n this._$type = def;\n }\n else if (def instanceof MaybeType) {\n throw new TypeError(\"Format cannot be optional\");\n }\n else if (def instanceof Object) {\n this._$type = undefined; // object\n this._$fieldsMap = new Map();\n this._$fields = Object.keys(def).map((name) => {\n const f = new Field(name, def[name]);\n this._$fieldsMap.set(name, f); // also set map entry\n return f;\n });\n\n // set headers\n if (header === undefined) {\n this.header = $hashCode(this.f) as HeaderType; // automatic\n this._$header = this.header as number;\n }\n else if (header === null) {\n this.header = undefined; // headerless\n this._$header = undefined;\n }\n else if (isValidHeader(header)) {\n this.header = header; // manual\n this._$header = typeof header === \"number\" ? header : $strToHashCode(header);\n }\n else {\n throw new TypeError(\"Header must be 2-byte string, uint16, or null.\");\n }\n }\n else {\n throw new TypeError(\"Format must be object or Type\");\n }\n }\n\n // ----- Static methods: -----\n\n /**\n * Read the header of a buffer as a number.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeader = peekHeader;\n\n /**\n * Read the header of a buffer as a string.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeaderStr = peekHeaderStr;\n\n // ----- Accessors: -----\n\n /**\n * @example \"{uint8,str[]?}\"\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private get f(): string {\n if (this._$format === undefined) {\n this._$format = this._$fields !== undefined\n ? `{${this._$fields.map(v => v.f).join(\",\")}}`\n : `${this._$type}`;\n }\n\n return this._$format;\n }\n\n /** @internal */\n private static _$initWriter(): BufferWriter {\n if (cfg.useGlobalEncodingBuffer) {\n if (!BufferFormat._$globalWriter) {\n this._$globalWriter = new BufferWriter(cfg.encodingBufferMaxSize);\n }\n\n return this._$globalWriter;\n }\n\n return new BufferWriter(cfg.encodingBufferInitialSize);\n }\n\n /**\n * Encode an object into an existing byte array.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n */\n public encodeInto>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): Uint8Array {\n return bytes.subarray(0, this.encodeIntoLength(data, bytes));\n }\n\n /**\n * Encode an object into an existing byte array, without allocating a view.\n *\n * @returns the number of bytes written to the start of `bytes`\n * @throws if fails to encode value to schema, or `bytes` is too small\n */\n public encodeIntoLength>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): number {\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n const writer = this._$intoWriter?.$reset(bytes) ?? new BufferWriter(bytes);\n this._$intoWriter = undefined;\n\n try {\n this._$write(data, writer);\n\n return writer.$byteLength;\n }\n finally {\n this._$intoWriter = writer;\n }\n }\n\n /**\n * Encode an object to bytes.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n *\n * @param data - data to encode\n * @param preserveBytes - (default: `setTinybufConfig().safe`) When set to true, copies encoded\n * bytes to a new buffer. When set to false, returns an unsafe view of bytes but prevents\n * unnnecessary memory allocation and fragmentation.\n *\n * @returns a copy of encoded bytes\n * @throws if fails to encode value to schema\n */\n public encode>(\n data: TDecodedType,\n preserveBytes?: boolean,\n ): Uint8Array {\n if (!this._$writer) {\n // lazy init\n this._$writer = BufferFormat._$initWriter();\n }\n\n // reset\n this._$writer.$byteLength = 0;\n\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n this._$write(data, this._$writer);\n\n return (preserveBytes ?? cfg.safe)\n ? this._$writer.$copyBytes()\n : this._$writer.$viewBytes();\n }\n\n /**\n * Decode binary data into an existing object instance.\n * @throws if fails to decode bytes to schema.\n */\n public decodeInto>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial,\n ): TDecodedType {\n return this._$decode(bytes, obj);\n }\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer\n ): TDecodedType;\n /**\n * @deprecated use decodeInto() instead\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto: Partial,\n ): TDecodedType;\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto?: Partial | undefined,\n ): TDecodedType {\n return this._$decode(bytes, decodeInto);\n }\n\n /**\n * Set additional transform functions to apply before encoding and after decoding.\n */\n public setTransforms(transforms: TransformConfig | Transforms): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof transforms === \"function\" || (Array.isArray(transforms) && typeof transforms[0] === \"function\")) {\n this._$transforms = transforms;\n }\n else {\n for (const name of Object.keys(transforms)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set transforms for field '${name}'`);\n }\n\n // Set validation for object.\n field.$coder.setTransforms(transforms[name]);\n }\n }\n\n return this;\n }\n\n /**\n * Set additional validation rules which are applied on encode() and decode().\n *\n * - Validation functions should throw an error, return an error, or return boolean false.\n * - Anything else is treated as successfully passing validation.\n */\n public setValidation(validations: ValidationConfig | ValidationFn): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof validations === \"function\") {\n this._$validate = validations;\n }\n else {\n for (const name of Object.keys(validations)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set validation function for field '${name}'`);\n }\n\n field.$coder.setValidation(validations[name]);\n }\n }\n\n return this;\n }\n\n // ----- Implementation: -----\n\n /** @internal */\n private _$decode(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial | undefined,\n ): TDecodedType {\n const headerBytes = this.header === undefined ? 0 : 2;\n\n const reader = this._$reader?.$reset(bytes, headerBytes) ?? new BufferReader(bytes, headerBytes);\n this._$reader = undefined;\n\n try {\n return this._$read(reader, obj);\n }\n finally {\n this._$reader = reader;\n }\n }\n\n /**\n * @param value\n * @param bw\n * @throws if the value is invalid\n *\n * @internal\n */\n private _$write(value: any, bw: BufferWriter): void {\n // write header\n if (this._$header !== undefined) bw.$writeUint16(this._$header);\n\n // write scalar\n if (this._$type !== undefined) {\n const safeValue = (this._$validate || this._$transforms) ? this._$preprocess(value) : value;\n\n return writers[this._$type](safeValue, bw);\n }\n\n // check for object type\n if (typeof value !== \"object\" || !value) {\n throw new TypeError(\"expected object type\");\n }\n\n // write each field\n const fields = this._$fields;\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const subValue = value[field.$name];\n\n if (field.$isOptional) {\n if (subValue === undefined || subValue === null) {\n coders.boolCoder.$write(false, bw);\n continue; // skip\n }\n else {\n coders.boolCoder.$write(true, bw);\n }\n }\n else if (subValue == null) {\n throw new Error(`missing required value: ${field.$name}`);\n }\n\n if (field.$isArray) {\n // array\n this._$writeArray(subValue, bw, field.$coder);\n continue;\n }\n\n // scalar/object field\n field.$coder._$write(subValue, bw);\n }\n }\n\n /**\n * pre-process: validation and/or transforms\n * @internal\n */\n private _$preprocess>(data: T): T {\n if (this._$validate) this._$processValidation(data);\n\n if (typeof this._$transforms === \"function\") {\n return this._$transforms(data);\n }\n else if (Array.isArray(this._$transforms) && typeof this._$transforms[0] === \"function\") {\n return this._$transforms[0](data);\n }\n\n return data;\n }\n\n /**\n * post-process: validation and/or transforms\n * @internal\n */\n private _$postprocess>(data: T): T {\n if (Array.isArray(this._$transforms) && typeof this._$transforms[1] === \"function\") {\n data = this._$transforms[1](data);\n }\n\n if (this._$validate) this._$processValidation(data);\n\n return data;\n }\n\n private _$processValidation(data: any): void {\n if (!this._$validate) return;\n const res = this._$validate(data);\n if (res instanceof Error) throw res;\n if (res === false) throw new Error(\"failed validation\");\n }\n\n /**\n * This function will be executed only the first time\n * After that, we'll compile the read routine and add it directly to the instance\n * @param state\n * @returns\n * @throws if fails\n *\n * @internal\n */\n private _$read>(state: BufferReader, obj?: Partial): TDecodedType {\n // This function will be executed only the first time to compile the read routine.\n // After that, we'll compile the read routine and add it directly to the instance\n\n // Update the read method implementation.\n this._$read = this._$compileFormatReadFn();\n\n return this._$read(state, obj);\n }\n\n /**\n * Generate read function code for this coder.\n *\n * @example\n * let v=o??{};\n * v.prop1=this._$readField(0,s,o);\n * v.prop2=this._$readField(1,s,o);\n * return v\n *\n * @internal\n */\n private _$makeObjectReadFnBody(): string {\n const fieldsStr: string = this._$fields\n .map(({ $name: n }, i) => `v.${n}=this.${this._$readField.name}(${i},s,v.${n})`)\n .join(\";\");\n\n return `let v=o??{};${fieldsStr};return v;`;\n }\n\n /**\n * Read an individual field.\n * @internal\n */\n private _$readField(fieldIndex: number, state: BufferReader, obj?: any): any {\n const field = this._$fields[fieldIndex];\n\n if (field.$isOptional && !coders.boolCoder.$read(state)) {\n return undefined;\n }\n\n if (field.$isArray) {\n return this._$readArray(field.$coder, state, obj);\n }\n\n return field.$coder._$read(state, obj);\n }\n\n /**\n * Compile the decode() method for this object.\n *\n * @internal\n */\n private _$compileFormatReadFn>(): (state: BufferReader, obj: Partial | undefined) => TDecodedType {\n if (this._$type !== undefined) {\n // scalar type\n return this._$hasValidationOrTransforms\n ? (s) => this._$postprocess(readers[this._$type](s))\n : readers[this._$type];\n }\n\n // object type\n return new Function(\"s\", \"o\", this._$makeObjectReadFnBody()) as any;\n }\n\n /**\n * @internal\n */\n private _$writeArray(value: any[], bw: BufferWriter, type: BufferFormat): void {\n if (!Array.isArray(value)) {\n throw new TypeError(`expected array, instead got: ${value}`);\n }\n\n coders.uintCoder.$write(value.length, bw);\n for (let i = 0; i < value.length; i++) {\n type._$write(value[i], bw);\n }\n }\n\n /**\n * @throws if invalid data\n * @internal\n */\n private _$readArray(type: BufferFormat, state: any, obj?: Array): Array {\n const len = coders.uintCoder.$read(state);\n const arr = Array.isArray(obj) ? obj : new Array(len);\n if (arr.length !== len) arr.length = len;\n for (let j = 0; j < arr.length; j++) {\n arr[j] = type._$read(state, obj?.[j]);\n }\n return arr;\n }\n}\n\n/**\n * Parses and represents an object field.\n *\n * @internal\n */\nclass Field {\n public $name: string;\n public $coder: BufferFormat;\n public $isOptional: boolean;\n public $isArray: boolean;\n\n private _$formatString?: string;\n\n public constructor(name: string, rawType: FieldDefinition) {\n this.$isOptional = rawType instanceof MaybeType;\n let type = rawType instanceof MaybeType ? rawType.type : rawType;\n\n this.$name = name;\n\n if (Array.isArray(type)) {\n if (type.length !== 1) {\n throw new TypeError(\"Array type must contain exactly one format\");\n }\n\n type = type[0];\n this.$isArray = true;\n }\n else {\n this.$isArray = false;\n }\n\n this.$coder = new BufferFormat(type, null);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public get f(): string {\n if (this._$formatString === undefined) {\n this._$formatString = `${(this.$coder as any).f}${this.$isArray ? \"[]\" : \"\"}${this.$isOptional ? \"?\" : \"\"}`;\n }\n\n return this._$formatString;\n }\n}\n"],"names":["TinybufError","Error","$hashCode","str","hash","i","length","charCodeAt","$strToHashCode","$hashCodeToStr","hashCode","String","fromCharCode","Math","floor","peekHeader","b","byteLength","RangeError","Uint8Array","DataView","getUint16","u8","ArrayBuffer","isView","buffer","byteOffset","peekHeaderStr","BufferParser","constructor","this","_$formats","Map","_$data","processBuffer","f","data","cb","r","header","has","get","_a","decode","set","e","err","stack","on","format","callback","decodeInPlace","ignore","forEach","clear","$floor","$ceil","ceil","$clamp","value","min","max","$roundTowardZero","x","$roundAwayFromZero","$touscal8","$toscal8","$fromuscal8","$fromscal8","Type","UInt","UInt8","UInt16","UInt32","Int","Int8","Int16","Int32","Float64","Float32","Float16","BFloat16","Scalar8","UScalar8","Bool","Bools","Buffer","JSON","RegExp","Date","ValidTypes","Object","values","MaybeType","type","mask","padBit","reduce","n","unmask","l","len","undefined","clz32","Array","isArray","val","$utf8encode","encoder","TextEncoder","encode","$utf8decode","decoder","TextDecoder","y","$tof16","Float32Array","Int32Array","s","z","$fromf16","pow","d","m","Infinity","NaN","Uint32Array","MAX_VARUINT32","MAX_VARINT32","POW_32","uintCoder","$write","writer","Number","$writeUint8","$writeUint16","$writeUint32","$read","reader","firstByte","$peek","$readUint32","$readUint16","$skip","uint8Coder","$readUint8","uint16Coder","uint32Coder","intCoder","int8Coder","$writeInt8","$readInt8","int16Coder","$writeInt16","$readInt16","int32Coder","$writeInt32","$readInt32","bfloat16Coder","$tobf16","$frombf16","float16Coder","float32Coder","$writeFloat32","$readFloat32","float64Coder","$writeFloat64","$readFloat64","uscalar8Coder","scalar8Coder","dateCoder","getTime","bufferCoder","$writeBytes","$readBytes","stringCoder","boolCoder","boolsCoder","slice","p","jsonCoder","stringify","parse","regexCoder","global","ignoreCase","multiline","source","g","writers","readers","cfg","safe","useGlobalEncodingBuffer","encodingBufferMaxSize","encodingBufferInitialSize","encodingBufferIncrement","BufferWriter","$0","$byteLength","_$writeHead","_$resizable","_$bytes","_$base","_$dataView","$reset","$viewBytes","subarray","$copyBytes","buf","_$pre","setInt8","setInt16","setInt32","setUint8","setUint16","setUint32","setFloat32","setFloat64","bytes","_$malloc","currentBytes","minNewBytes","availableBytes","increment","newBytes","newSize","BufferReader","headerBytes","offset","dv","_$byteLength","getUint8","_$at","getUint32","getInt8","getInt16","getInt32","getFloat32","getFloat64","BufferFormat","def","_$hasValidationOrTransforms","includes","_$type","TypeError","_$fieldsMap","_$fields","keys","map","name","Field","_$header","isValidHeader","h","isInteger","_$format","v","join","_$initWriter","_$globalWriter","encodeInto","encodeIntoLength","_$preprocess","_b","_$intoWriter","_$write","preserveBytes","_$writer","decodeInto","obj","_$decode","setTransforms","transforms","_$transforms","field","$coder","setValidation","validations","_$validate","_$reader","_$read","bw","safeValue","fields","subValue","$name","$isOptional","coders.boolCoder","$isArray","_$writeArray","_$processValidation","_$postprocess","res","state","_$compileFormatReadFn","_$makeObjectReadFnBody","fieldsStr","_$readField","fieldIndex","_$readArray","Function","coders.uintCoder","arr","j","rawType","_$formatString","bf16round","defineFormat","a","f16round","optional","t","scalround","c","assign","uscalround"],"mappings":"AAEM,MAAOA,qBAAqBC,OCM5B,SAAUC,UAAUC,GACxB,IAAIC,EAAO,KACX,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAC9BD,EAAe,GAAPA,EAAaD,EAAII,WAAWF,GAEtC,OAAc,MAAPD,CACT,CAQM,SAAUI,eAAeL,GAC7B,OAAmB,IAAfA,EAAIG,OAAqBJ,UAAUC,GACZ,IAApBA,EAAII,WAAW,GAAWJ,EAAII,WAAW,EAClD,CAKM,SAAUE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AKmQ,IAAW,CACjB,MAECnQ,KAAKmQ,IAAW,EAGlBnQ,KAAKsP,GAAS,IAAIpC,aAAkBlJ,EAAM,KAC3C,CAGD,KAAW3D,GAKT,YAJ4BmE,IAAxBxE,KAAKoR,KACPpR,KAAKoR,GAAiB,GAAIpR,KAAKsP,GAAejP,IAAIL,KAAKmQ,GAAW,KAAO,KAAKnQ,KAAKiQ,GAAc,IAAM,MAGlGjQ,KAAKoR,EACb,qELlmBG,SAAUC,UAAUpP,GAGxB,OAFA5B,EAAE,GAAK4B,EACP1D,EAAE,GAAY,WAAPA,EAAE,GACF8B,EAAE,EACX,uBPQ4B,IAAoB,IAAIP,kCYoCpC,SAAAwR,aAAoFC,EAAoBrS,GACtH,OAAa,OAANqS,GAA2B,iBAANA,EACxB,IAAIrE,aAA4BqE,GAChC,IAAIrE,aAA4BhO,EAAQqS,EAC9C,mBNvDM,SAAUC,SAASvP,GACvB,OAAOyD,EAASL,EAAOpD,GACzB,qCHgJM,SAAUwP,SAAoCC,GAClD,OAAO,IAAI3N,UAAU2N,EACvB,sFDxIM,SAAUC,UAAU1P,GACxB,OAAOK,WAAWF,SAASH,GAC7B,2BOdiC2P,IAC/B3H,EAAWpG,OAAAgO,OAAAhO,OAAAgO,OAAA,GAAA5H,GAAQ2H,EAAG,2CPElB,SAAUE,WAAW7P,GACzB,OAAOI,YAAYF,UAAUF,GAC/B"} \ No newline at end of file diff --git a/dist/index.mjs b/dist/index.mjs index 6e0dea3..81596d4 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -1,2 +1,2 @@ -class TinybufError extends Error{}function $hashCode(t){let r=5381;for(let e=0;enew BufferParser;class BufferParser{constructor(){this.t=new Map,this.o=new Map}processBuffer(t){var r;let e,i,n,s;try{const o=peekHeader(t);if(!this.t.has(o))throw new TinybufError(`Unknown format: ${o} '${$hashCodeToStr(o)}')`);[e,n,s]=this.t.get(o),s&&(i=null!==(r=this.o.get(o))&&void 0!==r?r:{}),i=e.decode(t,i),s&&this.o.set(o,i)}catch(t){const r=new TinybufError(`Failed to decode: ${t}`);throw r.stack=t.stack,r}n(i)}on(t,r,{decodeInPlace:e=!1}={}){var i;if(null==t.header)throw new TinybufError("Format requires header");const n="string"==typeof t.header?$strToHashCode(t.header):t.header;if(this.t.has(n)&&(null===(i=this.t.get(n))||void 0===i?void 0:i[0])!==t)throw new TinybufError(`Format header collision: ${t.header}`);return this.t.set(n,[t,r,e]),this}ignore(...t){return t.forEach((t=>this.on(t,(()=>{})))),this}clear(){this.t.clear(),this.o.clear()}}const t=Math.floor,r=Math.ceil,$clamp=(t,r,e)=>t>e?e:te<0?r(e):t(e),$roundAwayFromZero=e=>e<0?t(e):r(e);function uscalround(t){return $fromuscal8($touscal8(t))}function scalround(t){return $fromscal8($toscal8(t))}function $touscal8(t){return $clamp(127+$roundTowardZero(254*t-127),0,254)}function $toscal8(t){return $clamp($roundTowardZero(127*t),-127,127)+127}function $fromuscal8(t){return $clamp(.01*($roundAwayFromZero(.3937007874015748*(t-127))+50),0,1)}function $fromscal8(t){return $clamp(.01*$roundAwayFromZero(.787401574803149*(t-127)),-1,1)}const e={UInt:"uint",UInt8:"u8",UInt16:"u16",UInt32:"u32",Int:"int",Int8:"i8",Int16:"i16",Int32:"i32",Float64:"f64",Float32:"f32",Float16:"f16",BFloat16:"b16",Scalar8:"sc",UScalar8:"usc",Bool:"bl",Bools:"bls",Buffer:"buf",String:"str",JSON:"jsn",RegExp:"re",Date:"dt"},i=Object.values(e);class MaybeType{constructor(t){this.type=t}}function optional(t){return new MaybeType(t)}const mask=(t,r=1)=>t.reduce(((t,r)=>t<<1|r),r),unmask=(t,r)=>{const e=void 0===r?31-Math.clz32(t):Array.isArray(r)?r.length:r,i=Array.isArray(r)&&r.length===e?r:new Array(e);for(let r=0;rt.encode(r)}(),s=function(){const t=new TextDecoder("utf-8");return r=>t.decode(r)}();function f16round(t){return h(o(t))}const o=function(){const t=new Float32Array(1),r=new Int32Array(t.buffer);return function(e){t[0]=e;let i=r[0],n=i>>16&32768,s=4096+(2147483647&i)|0;return s>=1199570944?(2147483647&i)<1199570944?31743|n:s<2139095040?31744|n:31744|n|(8388607&i)>>13:s>=947912704?n|s-939524096>>13:s<855638016?n:(s=(2147483647&i)>>23,n|(8388607&i|8388608)+(8388608>>>s-102)>>126-s)}}(),h=function(){const t=Math.pow(2,-24),r=new Float32Array(1056);for(let t=0;t<32;t++)r[t]=Math.pow(2,t-15);for(let t=0;t<1024;t++)r[t+32]=1+t/1024;return function(e){const i=32768&~e?1:-1,n=31744&e,s=1023&e;return 0===n?0===s?0*i:i*t:31744===n?0===s?i*(1/0):NaN:r[n>>10]*r[s+32]*i}}(),a=new Uint32Array(1),u=new Float32Array(a.buffer);function bf16round(t){return u[0]=t,a[0]=4294901760&a[0],u[0]}const f=536870912,c=268435456,d=4294967296,l={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r<0&&(r=0),r<128?e.u(r):r<16384?e.l(r+32768):r=f?(e.$(t(r/d)+3758096384),e.$(r>>>0)):e.u(!0===r?1:0)},p:t=>{const r=t.m();return 128&r?64&r?32&r?(t.v()-3758096384)*d+t.v():t.v()-3221225472:t.F()-32768:(t.B(),r)}},$={h:(t,r)=>r.u(t),p:t=>t.A()},w={h:(t,r)=>r.l(t),p:t=>t.F()},y={h:(t,r)=>r.$(t),p:t=>t.v()},p={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r>=-64&&r<64?e.u(127&r):r>=-8192&&r<8192?e.l(32768+(16383&r)):r>=-268435456&&r=c?(e.$(3758096384+(536870911&t(r/d))),e.$(r>>>0)):e.u(!0===r?127:0)},p:t=>{let r,e=t.m();return 128&e?64&e?32&e?(r=t.v()-3758096384,r=268435456&r?3758096384|r:r,r*d+t.v()):(r=t.v()-3221225472,268435456&r?3758096384|r:r):(r=t.F()-32768,8192&r?4294950912|r:r):(t.B(),64&e?4294967168|e:e)}},b={h:(t,r)=>r.T(t),p:t=>t.U()},m={h:(t,r)=>r.I(t),p:t=>t.M()},v={h:(t,r)=>r.S(t),p:t=>t._()},F={h:(t,r)=>r.l(function $tobf16(t){return u[0]=t,a[0]>>>16}(t)),p:t=>function $frombf16(t){return a[0]=t<<16,u[0]}(t.F())},B={h:(t,r)=>r.l(o(t)),p:t=>h(t.F())},A={h:(t,r)=>r.j(t),p:t=>t.H()},T={h:(t,r)=>r.k(t),p:t=>t.O()},E={h:(t,r)=>r.u($touscal8(t)),p:t=>$fromuscal8(t.A())},g={h:(t,r)=>r.u($toscal8(t)),p:t=>$fromscal8(t.A())},U={h:(t,r)=>p.h(t.getTime(),r),p:t=>new Date(p.p(t))},I={h:(t,r)=>{l.h(t.byteLength,r),r.C(t)},p:t=>t.D(l.p(t))},M={h:(t,r)=>I.h(n(t),r),p:t=>s(I.p(t))},S={h:(t,r)=>r.u(t?1:0),p:t=>0!==t.A()},x={h:(t,r)=>{t.length>28&&(t=t.slice(0,28)),l.h(mask(t),r)},p:(t,r)=>unmask(l.p(t),r)},_={h:(t,r)=>M.h(JSON.stringify(t),r),p:t=>JSON.parse(M.p(t))},j={h:(t,r)=>{r.u(mask([t.global,t.ignoreCase,t.multiline])),M.h(t.source,r)},p:t=>{const[r,e,i]=unmask(t.A());return new RegExp(M.p(t),(r?"g":"")+(e?"i":"")+(i?"m":""))}},H={[e.UInt]:l.h,[e.UInt8]:$.h,[e.UInt16]:w.h,[e.UInt32]:y.h,[e.Int]:p.h,[e.Int8]:b.h,[e.Int16]:m.h,[e.Int32]:v.h,[e.Float64]:T.h,[e.Float32]:A.h,[e.Float16]:B.h,[e.BFloat16]:F.h,[e.Scalar8]:g.h,[e.UScalar8]:E.h,[e.Bool]:S.h,[e.Bools]:x.h,[e.Buffer]:I.h,[e.String]:M.h,[e.JSON]:_.h,[e.RegExp]:j.h,[e.Date]:U.h},k={[e.UInt]:l.p,[e.UInt8]:$.p,[e.UInt16]:w.p,[e.UInt32]:y.p,[e.Int]:p.p,[e.Int8]:b.p,[e.Int16]:m.p,[e.Int32]:v.p,[e.Float64]:T.p,[e.Float32]:A.p,[e.Float16]:B.p,[e.BFloat16]:F.p,[e.Scalar8]:g.p,[e.UScalar8]:E.p,[e.Bool]:S.p,[e.Bools]:x.p,[e.Buffer]:I.p,[e.String]:M.p,[e.JSON]:_.p,[e.RegExp]:j.p,[e.Date]:U.p},setTinybufConfig=t=>{O=Object.assign(Object.assign({},O),t)};let O={safe:!1,useGlobalEncodingBuffer:!0,encodingBufferMaxSize:1500,encodingBufferInitialSize:256,encodingBufferIncrement:256};class BufferWriter{constructor(t){this.R=0,this.V=0,this.N="number"==typeof t;let r=t instanceof Uint8Array?t:new Uint8Array(t);this.W=r,this.J=r.byteOffset,this.P=new DataView(r.buffer)}q(t){return this.P.buffer!==t.buffer&&(this.P=new DataView(t.buffer)),this.W=t,this.J=t.byteOffset,this.N=!1,this.V=0,this.R=0,this}G(){return this.W.subarray(0,this.R)}L(){const t=new Uint8Array(this.R);return t.set(this.G()),t}T(t){this.K(1).setInt8(this.V,t)}I(t){this.K(2).setInt16(this.V,t,!0)}S(t){this.K(4).setInt32(this.V,t,!0)}u(t){this.K(1).setUint8(this.V,t)}l(t){this.K(2).setUint16(this.V,t,!1)}$(t){this.K(4).setUint32(this.V,t,!1)}j(t){this.K(4).setFloat32(this.V,t,!0)}k(t){this.K(8).setFloat64(this.V,t,!0)}C(t){this.K(t.byteLength),this.W.set(t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this.V-this.J)}K(t){return this.R+t>this.W.byteLength&&this.X(t),this.V=this.J+this.R,this.R+=t,this.P}X(t){if(!this.N)throw new TinybufError("exceeded buffer length: "+this.W.byteLength);const r=this.W.byteLength,e=this.R+t-r,i=O.encodingBufferMaxSize-r;if(e>i)throw new TinybufError("exceeded encodingBufferMaxSize: "+O.encodingBufferMaxSize);const n=O.encodingBufferIncrement,s=Math.ceil(e/n)*n,o=r+Math.min(s,i),h=new Uint8Array(o);h.set(this.W),this.P=new DataView(h.buffer),this.W=h,this.J=0}}class BufferReader{constructor(t,r){this.q(t,r)}q(t,r){const e=ArrayBuffer.isView(t),i=e?t.buffer:t,n=e?t.byteOffset:0;let s=this.P;return(void 0===s||s.buffer!==i||ns.byteOffset+s.byteLength)&&(s=this.P=t instanceof DataView?t:new DataView(i)),this.J=n-s.byteOffset,this.Y=t.byteLength,this.i=null!=r?r:0,this}m(){if(this.i>=this.Y)throw new RangeError("exceeded bytes");return this.P.getUint8(this.J+this.i)}B(){this.i++}A(){return this.P.getUint8(this.Z(1))}F(){return this.P.getUint16(this.Z(2))}v(){return this.P.getUint32(this.Z(4))}U(){return this.P.getInt8(this.Z(1))}M(){return this.P.getInt16(this.Z(2),!0)}_(){return this.P.getInt32(this.Z(4),!0)}H(){return this.P.getFloat32(this.Z(4),!0)}O(){return this.P.getFloat64(this.Z(8),!0)}D(t){return new Uint8Array(this.P.buffer,this.P.byteOffset+this.Z(t),t)}Z(t){const r=this.i;if(r+t>this.Y)throw new RangeError("exceeded bytes");return this.i=r+t,this.J+r}}function defineFormat(t,r){return null!==t&&"object"==typeof t?new BufferFormat(t):new BufferFormat(r,t)}class BufferFormat{constructor(t,r){if(this.tt=!1,"string"==typeof t&&i.includes(t))this.rt=t;else{if(t instanceof MaybeType)throw new TypeError("Format cannot be optional");if(!(t instanceof Object))throw new TypeError("Format must be object or Type");if(this.rt=void 0,this.et=new Map,this.it=Object.keys(t).map((r=>{const e=new Field(r,t[r]);return this.et.set(r,e),e})),void 0===r)this.header=$hashCode(this.f),this.nt=this.header;else if(null===r)this.header=void 0,this.nt=void 0;else{if(!function isValidHeader(t){return"number"==typeof t?Number.isInteger(t)&&t>=0&&t<=65535:"string"==typeof t&&2===(new TextEncoder).encode(t).byteLength}(r))throw new TypeError("Header must be 2-byte string, uint16, or null.");this.header=r,this.nt="number"==typeof r?r:$strToHashCode(r)}}}get f(){return void 0===this.st&&(this.st=void 0!==this.it?`{${this.it.map((t=>t.f)).join(",")}}`:`${this.rt}`),this.st}static ot(){return O.useGlobalEncodingBuffer?(BufferFormat.ht||(this.ht=new BufferWriter(O.encodingBufferMaxSize)),this.ht):new BufferWriter(O.encodingBufferInitialSize)}encodeInto(t,r){return r.subarray(0,this.encodeIntoLength(t,r))}encodeIntoLength(t,r){var e,i;this.tt&&(t=this.ut(t));const n=null!==(i=null===(e=this.ft)||void 0===e?void 0:e.q(r))&&void 0!==i?i:new BufferWriter(r);this.ft=void 0;try{return this.ct(t,n),n.R}finally{this.ft=n}}encode(t,r){return this.dt||(this.dt=BufferFormat.ot()),this.dt.R=0,this.tt&&(t=this.ut(t)),this.ct(t,this.dt),(null!=r?r:O.safe)?this.dt.L():this.dt.G()}decodeInto(t,r){return this.lt(t,r)}decode(t,r){return this.lt(t,r)}setTransforms(t){if(this.tt=!0,"function"==typeof t||Array.isArray(t)&&"function"==typeof t[0])this.$t=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set transforms for field '${r}'`);e.wt.setTransforms(t[r])}return this}setValidation(t){if(this.tt=!0,"function"==typeof t)this.yt=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set validation function for field '${r}'`);e.wt.setValidation(t[r])}return this}lt(t,r){var e,i;const n=void 0===this.header?0:2,s=null!==(i=null===(e=this.bt)||void 0===e?void 0:e.q(t,n))&&void 0!==i?i:new BufferReader(t,n);this.bt=void 0;try{return this.vt(s,r)}finally{this.bt=s}}ct(t,r){if(void 0!==this.nt&&r.l(this.nt),void 0!==this.rt){const e=this.yt||this.$t?this.ut(t):t;return H[this.rt](e,r)}if("object"!=typeof t||!t)throw new TypeError("expected object type");for(const e of this.it){const i=t[e.Ft];if(e.Bt){if(null==i){S.h(!1,r);continue}S.h(!0,r)}else if(null==i)throw new Error(`missing required value: ${e.Ft}`);e.At?this.Tt(i,r,e.wt):e.wt.ct(i,r)}}ut(t){return this.yt&&this.Et(t),"function"==typeof this.$t?this.$t(t):Array.isArray(this.$t)&&"function"==typeof this.$t[0]?this.$t[0](t):t}gt(t){return Array.isArray(this.$t)&&"function"==typeof this.$t[1]&&(t=this.$t[1](t)),this.yt&&this.Et(t),t}Et(t){if(!this.yt)return;const r=this.yt(t);if(r instanceof Error)throw r;if(!1===r)throw new Error("failed validation")}vt(t,r){return this.vt=this.Ut(),this.vt(t,r)}It(){const t=this.it.map((({Ft:t},r)=>`v.${t}=this.${this.Mt.name}(${r},s,v.${t})`)).join(";");return`let v=o??{};${t};return v;`}Mt(t,r,e){const i=this.it[t];if(!i.Bt||S.p(r))return i.At?this.St(i.wt,r,e):i.wt.vt(r,e)}Ut(){return void 0!==this.rt?this.tt?t=>this.gt(k[this.rt](t)):k[this.rt]:new Function("s","o",this.It())}Tt(t,r,e){if(!Array.isArray(t))throw new TypeError(`expected array, instead got: ${t}`);l.h(t.length,r);for(let i=0;inew BufferParser;class BufferParser{constructor(){this.t=new Map,this.o=new Map}processBuffer(t){var r;let e,i,n,s;try{const o=peekHeader(t);if(!this.t.has(o))throw new TinybufError(`Unknown format: ${o} '${$hashCodeToStr(o)}')`);[e,n,s]=this.t.get(o),s&&(i=null!==(r=this.o.get(o))&&void 0!==r?r:{}),i=e.decode(t,i),s&&this.o.set(o,i)}catch(t){const r=new TinybufError(`Failed to decode: ${t}`);throw r.stack=t.stack,r}n(i)}on(t,r,{decodeInPlace:e=!1}={}){var i;if(null==t.header)throw new TinybufError("Format requires header");const n="string"==typeof t.header?$strToHashCode(t.header):t.header;if(this.t.has(n)&&(null===(i=this.t.get(n))||void 0===i?void 0:i[0])!==t)throw new TinybufError(`Format header collision: ${t.header}`);return this.t.set(n,[t,r,e]),this}ignore(...t){return t.forEach((t=>this.on(t,(()=>{})))),this}clear(){this.t.clear(),this.o.clear()}}const t=Math.floor,r=Math.ceil,$clamp=(t,r,e)=>t>e?e:te<0?r(e):t(e),$roundAwayFromZero=e=>e<0?t(e):r(e);function uscalround(t){return $fromuscal8($touscal8(t))}function scalround(t){return $fromscal8($toscal8(t))}function $touscal8(t){return $clamp(127+$roundTowardZero(254*t-127),0,254)}function $toscal8(t){return $clamp($roundTowardZero(127*t),-127,127)+127}function $fromuscal8(t){return $clamp(.01*($roundAwayFromZero(.3937007874015748*(t-127))+50),0,1)}function $fromscal8(t){return $clamp(.01*$roundAwayFromZero(.787401574803149*(t-127)),-1,1)}const e={UInt:"uint",UInt8:"u8",UInt16:"u16",UInt32:"u32",Int:"int",Int8:"i8",Int16:"i16",Int32:"i32",Float64:"f64",Float32:"f32",Float16:"f16",BFloat16:"b16",Scalar8:"sc",UScalar8:"usc",Bool:"bl",Bools:"bls",Buffer:"buf",String:"str",JSON:"jsn",RegExp:"re",Date:"dt"},i=Object.values(e);class MaybeType{constructor(t){this.type=t}}function optional(t){return new MaybeType(t)}const mask=(t,r=1)=>t.reduce(((t,r)=>t<<1|r),r),unmask=(t,r)=>{const e=void 0===r?31-Math.clz32(t):Array.isArray(r)?r.length:r,i=Array.isArray(r)&&r.length===e?r:new Array(e);for(let r=0;rt.encode(r)}(),s=function(){const t=new TextDecoder("utf-8");return r=>t.decode(r)}();function f16round(t){return h(o(t))}const o=function(){const t=new Float32Array(1),r=new Int32Array(t.buffer);return function(e){t[0]=e;let i=r[0],n=i>>16&32768,s=4096+(2147483647&i)|0;return s>=1199570944?(2147483647&i)<1199570944?31743|n:s<2139095040?31744|n:31744|n|(8388607&i)>>13:s>=947912704?n|s-939524096>>13:s<855638016?n:(s=(2147483647&i)>>23,n|(8388607&i|8388608)+(8388608>>>s-102)>>126-s)}}(),h=function(){const t=Math.pow(2,-24),r=new Float32Array(1056);for(let t=0;t<32;t++)r[t]=Math.pow(2,t-15);for(let t=0;t<1024;t++)r[t+32]=1+t/1024;return function(e){const i=32768&~e?1:-1,n=31744&e,s=1023&e;return 0===n?0===s?0*i:i*t:31744===n?0===s?i*(1/0):NaN:r[n>>10]*r[s+32]*i}}(),a=new Uint32Array(1),u=new Float32Array(a.buffer);function bf16round(t){return u[0]=t,a[0]=4294901760&a[0],u[0]}const f=536870912,c=268435456,d=4294967296,l={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r<0&&(r=0),r<128?e.u(r):r<16384?e.l(r+32768):r=f?(e.$(t(r/d)+3758096384|0),e.l(r>>>16),e.l(65535&r)):e.u(!0===r?1:0)},p:t=>{const r=t.m();return 128&r?64&r?32&r?(t.v()-3758096384)*d+t.v():t.v()-3221225472:t.F()-32768:(t.B(),r)}},$={h:(t,r)=>r.u(t),p:t=>t.A()},w={h:(t,r)=>r.l(t),p:t=>t.F()},y={h:(t,r)=>r.$(t),p:t=>t.v()},p={h:(r,e)=>{"number"!=typeof r&&(r=Number(r)),r>=-64&&r<64?e.u(127&r):r>=-8192&&r<8192?e.l(32768+(16383&r)):r>=-268435456&&r=c?(e.$(536870911&t(r/d)|3758096384),e.l(r>>>16),e.l(65535&r)):e.u(!0===r?127:0)},p:t=>{let r,e=t.m();return 128&e?64&e?32&e?(r=t.v()-3758096384,r=268435456&r?3758096384|r:r,r*d+t.v()):(r=t.v()-3221225472,268435456&r?3758096384|r:r):(r=t.F()-32768,8192&r?4294950912|r:r):(t.B(),64&e?4294967168|e:e)}},b={h:(t,r)=>r.T(t),p:t=>t.U()},m={h:(t,r)=>r.I(t),p:t=>t.M()},v={h:(t,r)=>r.S(t),p:t=>t._()},F={h:(t,r)=>r.l(function $tobf16(t){return u[0]=t,a[0]>>>16}(t)),p:t=>function $frombf16(t){return a[0]=t<<16,u[0]}(t.F())},B={h:(t,r)=>r.l(o(t)),p:t=>h(t.F())},A={h:(t,r)=>r.j(t),p:t=>t.H()},T={h:(t,r)=>r.k(t),p:t=>t.O()},E={h:(t,r)=>r.u($touscal8(t)),p:t=>$fromuscal8(t.A())},g={h:(t,r)=>r.u($toscal8(t)),p:t=>$fromscal8(t.A())},U={h:(t,r)=>p.h(t.getTime(),r),p:t=>new Date(p.p(t))},I={h:(t,r)=>{l.h(t.byteLength,r),r.C(t)},p:t=>t.D(l.p(t))},M={h:(t,r)=>I.h(n(t),r),p:t=>s(I.p(t))},S={h:(t,r)=>r.u(t?1:0),p:t=>0!==t.A()},x={h:(t,r)=>{t.length>28&&(t=t.slice(0,28)),l.h(mask(t),r)},p:(t,r)=>unmask(l.p(t),r)},_={h:(t,r)=>M.h(JSON.stringify(t),r),p:t=>JSON.parse(M.p(t))},j={h:(t,r)=>{r.u(mask([t.global,t.ignoreCase,t.multiline])),M.h(t.source,r)},p:t=>{const[r,e,i]=unmask(t.A());return new RegExp(M.p(t),(r?"g":"")+(e?"i":"")+(i?"m":""))}},H={[e.UInt]:l.h,[e.UInt8]:$.h,[e.UInt16]:w.h,[e.UInt32]:y.h,[e.Int]:p.h,[e.Int8]:b.h,[e.Int16]:m.h,[e.Int32]:v.h,[e.Float64]:T.h,[e.Float32]:A.h,[e.Float16]:B.h,[e.BFloat16]:F.h,[e.Scalar8]:g.h,[e.UScalar8]:E.h,[e.Bool]:S.h,[e.Bools]:x.h,[e.Buffer]:I.h,[e.String]:M.h,[e.JSON]:_.h,[e.RegExp]:j.h,[e.Date]:U.h},k={[e.UInt]:l.p,[e.UInt8]:$.p,[e.UInt16]:w.p,[e.UInt32]:y.p,[e.Int]:p.p,[e.Int8]:b.p,[e.Int16]:m.p,[e.Int32]:v.p,[e.Float64]:T.p,[e.Float32]:A.p,[e.Float16]:B.p,[e.BFloat16]:F.p,[e.Scalar8]:g.p,[e.UScalar8]:E.p,[e.Bool]:S.p,[e.Bools]:x.p,[e.Buffer]:I.p,[e.String]:M.p,[e.JSON]:_.p,[e.RegExp]:j.p,[e.Date]:U.p},setTinybufConfig=t=>{O=Object.assign(Object.assign({},O),t)};let O={safe:!1,useGlobalEncodingBuffer:!0,encodingBufferMaxSize:1500,encodingBufferInitialSize:256,encodingBufferIncrement:256};class BufferWriter{constructor(t){this.R=0,this.V=0,this.N="number"==typeof t;let r=t instanceof Uint8Array?t:new Uint8Array(t);this.W=r,this.J=r.byteOffset,this.P=new DataView(r.buffer)}q(t){return this.P.buffer!==t.buffer&&(this.P=new DataView(t.buffer)),this.W=t,this.J=t.byteOffset,this.N=!1,this.V=0,this.R=0,this}G(){return this.W.subarray(0,this.R)}L(){const t=new Uint8Array(this.R);return t.set(this.G()),t}T(t){this.K(1).setInt8(this.V,t)}I(t){this.K(2).setInt16(this.V,t,!0)}S(t){this.K(4).setInt32(this.V,t,!0)}u(t){this.K(1).setUint8(this.V,t)}l(t){this.K(2).setUint16(this.V,t,!1)}$(t){this.K(4).setUint32(this.V,t,!1)}j(t){this.K(4).setFloat32(this.V,t,!0)}k(t){this.K(8).setFloat64(this.V,t,!0)}C(t){this.K(t.byteLength),this.W.set(t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),this.V-this.J)}K(t){return this.R+t>this.W.byteLength&&this.X(t),this.V=this.J+this.R,this.R+=t,this.P}X(t){if(!this.N)throw new TinybufError("exceeded buffer length: "+this.W.byteLength);const r=this.W.byteLength,e=this.R+t-r,i=O.encodingBufferMaxSize-r;if(e>i)throw new TinybufError("exceeded encodingBufferMaxSize: "+O.encodingBufferMaxSize);const n=O.encodingBufferIncrement,s=Math.ceil(e/n)*n,o=r+Math.min(s,i),h=new Uint8Array(o);h.set(this.W),this.P=new DataView(h.buffer),this.W=h,this.J=0}}class BufferReader{constructor(t,r){this.q(t,r)}q(t,r){const e=ArrayBuffer.isView(t),i=e?t.buffer:t,n=e?t.byteOffset:0;let s=this.P;return(void 0===s||s.buffer!==i||ns.byteOffset+s.byteLength)&&(s=this.P=t instanceof DataView?t:new DataView(i)),this.J=n-s.byteOffset,this.Y=t.byteLength,this.i=null!=r?r:0,this}m(){if(this.i>=this.Y)throw new RangeError("exceeded bytes");return this.P.getUint8(this.J+this.i)}B(){this.i++}A(){return this.P.getUint8(this.Z(1))}F(){return this.P.getUint16(this.Z(2))}v(){return this.P.getUint32(this.Z(4))}U(){return this.P.getInt8(this.Z(1))}M(){return this.P.getInt16(this.Z(2),!0)}_(){return this.P.getInt32(this.Z(4),!0)}H(){return this.P.getFloat32(this.Z(4),!0)}O(){return this.P.getFloat64(this.Z(8),!0)}D(t){return new Uint8Array(this.P.buffer,this.P.byteOffset+this.Z(t),t)}Z(t){const r=this.i;if(r+t>this.Y)throw new RangeError("exceeded bytes");return this.i=r+t,this.J+r}}function defineFormat(t,r){return null!==t&&"object"==typeof t?new BufferFormat(t):new BufferFormat(r,t)}class BufferFormat{constructor(t,r){if(this.tt=!1,"string"==typeof t&&i.includes(t))this.rt=t;else{if(t instanceof MaybeType)throw new TypeError("Format cannot be optional");if(!(t instanceof Object))throw new TypeError("Format must be object or Type");if(this.rt=void 0,this.et=new Map,this.it=Object.keys(t).map((r=>{const e=new Field(r,t[r]);return this.et.set(r,e),e})),void 0===r)this.header=$hashCode(this.f),this.nt=this.header;else if(null===r)this.header=void 0,this.nt=void 0;else{if(!function isValidHeader(t){return"number"==typeof t?Number.isInteger(t)&&t>=0&&t<=65535:"string"==typeof t&&2===(new TextEncoder).encode(t).byteLength}(r))throw new TypeError("Header must be 2-byte string, uint16, or null.");this.header=r,this.nt="number"==typeof r?r:$strToHashCode(r)}}}get f(){return void 0===this.st&&(this.st=void 0!==this.it?`{${this.it.map((t=>t.f)).join(",")}}`:`${this.rt}`),this.st}static ot(){return O.useGlobalEncodingBuffer?(BufferFormat.ht||(this.ht=new BufferWriter(O.encodingBufferMaxSize)),this.ht):new BufferWriter(O.encodingBufferInitialSize)}encodeInto(t,r){return r.subarray(0,this.encodeIntoLength(t,r))}encodeIntoLength(t,r){var e,i;this.tt&&(t=this.ut(t));const n=null!==(i=null===(e=this.ft)||void 0===e?void 0:e.q(r))&&void 0!==i?i:new BufferWriter(r);this.ft=void 0;try{return this.ct(t,n),n.R}finally{this.ft=n}}encode(t,r){return this.dt||(this.dt=BufferFormat.ot()),this.dt.R=0,this.tt&&(t=this.ut(t)),this.ct(t,this.dt),(null!=r?r:O.safe)?this.dt.L():this.dt.G()}decodeInto(t,r){return this.lt(t,r)}decode(t,r){return this.lt(t,r)}setTransforms(t){if(this.tt=!0,"function"==typeof t||Array.isArray(t)&&"function"==typeof t[0])this.$t=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set transforms for field '${r}'`);e.wt.setTransforms(t[r])}return this}setValidation(t){if(this.tt=!0,"function"==typeof t)this.yt=t;else for(const r of Object.keys(t)){const e=this.et.get(r);if(!e)throw new TypeError(`Failed to set validation function for field '${r}'`);e.wt.setValidation(t[r])}return this}lt(t,r){var e,i;const n=void 0===this.header?0:2,s=null!==(i=null===(e=this.bt)||void 0===e?void 0:e.q(t,n))&&void 0!==i?i:new BufferReader(t,n);this.bt=void 0;try{return this.vt(s,r)}finally{this.bt=s}}ct(t,r){if(void 0!==this.nt&&r.l(this.nt),void 0!==this.rt){const e=this.yt||this.$t?this.ut(t):t;return H[this.rt](e,r)}if("object"!=typeof t||!t)throw new TypeError("expected object type");const e=this.it;for(let i=0;i`v.${t}=this.${this.Mt.name}(${r},s,v.${t})`)).join(";");return`let v=o??{};${t};return v;`}Mt(t,r,e){const i=this.it[t];if(!i.Bt||S.p(r))return i.At?this.St(i.wt,r,e):i.wt.vt(r,e)}Ut(){return void 0!==this.rt?this.tt?t=>this.gt(k[this.rt](t)):k[this.rt]:new Function("s","o",this.It())}Tt(t,r,e){if(!Array.isArray(t))throw new TypeError(`expected array, instead got: ${t}`);l.h(t.length,r);for(let i=0;i;\ntype Uint16FormatHeader = number;\n\n/**\n * Small utility for registering and processing format handlers.\n *\n * @example\n * const myHandler = bufferParser()\n * .on(FormatA, aData => {})\n * .on(FormatB, bData => {});\n *\n * myHandler.processBuffer(bytes);\n */\nexport const bufferParser = (): BufferParser => new BufferParser();\n\nexport class BufferParser {\n /** @internal */\n private _$formats = new Map any, decodeInPlace: boolean]>();\n private _$data = new Map(); // used when decoding in-place\n\n /**\n * Decode an array buffer and trigger the relevant data handler.\n *\n * When passed an ArrayBufferView, accesses the underlying 'buffer' instance directly.\n *\n * @throws {TinybufError} if fails to decode, or no handler is registered\n */\n public processBuffer(b: ArrayBuffer | ArrayBufferView): void {\n let f: any, data: any, cb: (data: any) => any, r: boolean;\n\n try {\n const header = peekHeader(b);\n\n if (!this._$formats.has(header)) {\n throw new TinybufError(`Unknown format: ${header} '${$hashCodeToStr(header)}')`);\n }\n\n [f, cb, r] = this._$formats.get(header);\n if (r) data = this._$data.get(header) ?? {};\n data = f.decode(b, data);\n if (r) this._$data.set(header, data);\n }\n catch (e) {\n const err = new TinybufError(`Failed to decode: ${e}`);\n err.stack = e.stack;\n\n throw err;\n }\n\n cb(data);\n }\n\n /**\n * Register a format handler.\n */\n public on>(\n format: BufferFormat,\n callback: (data: TDecodedType) => any,\n {\n decodeInPlace = false,\n } = {},\n ): this {\n if (format.header == null) {\n throw new TinybufError(\"Format requires header\");\n }\n\n const header = typeof format.header === \"string\" ? $strToHashCode(format.header) : format.header;\n\n if (this._$formats.has(header) && this._$formats.get(header)?.[0] !== format) {\n throw new TinybufError(`Format header collision: ${format.header}`);\n }\n\n this._$formats.set(header, [format, callback, decodeInPlace]);\n\n return this;\n }\n\n /** Register a format (or formats) that are recognized. */\n public ignore(...format: AnyFormat[]): this {\n format.forEach(f => this.on(f, () => {}));\n return this;\n }\n\n /** Clears all registered formats and handlers. */\n public clear(): void {\n this._$formats.clear();\n this._$data.clear();\n }\n}\n","export const $floor = Math.floor,\n $ceil = Math.ceil;\n\n/** Clamp a number to a range. */\nexport const $clamp = (value: number, min: number, max: number): number =>\n value > max ? max : value < min ? min : value;\n\n/** Round toward zero */\nexport const $roundTowardZero = (x: number): number => x < 0 ? $ceil(x) : $floor(x);\n\n/** Round away zero */\nexport const $roundAwayFromZero = (x: number): number =>\n x < 0 ? $floor(x) : $ceil(x);\n","import { $clamp, $roundTowardZero, $roundAwayFromZero } from \"./math\";\n\n/**\n * Quantize a number to an 8-bit scalar between 0.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function uscalround(x: number): number {\n return $fromuscal8($touscal8(x));\n}\n\n/**\n * Quantize a number to an 8-bit signed scalar between -1.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function scalround(x: number): number {\n return $fromscal8($toscal8(x));\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $touscal8(x: number): number {\n return $clamp(127 + $roundTowardZero(x * 254 - 127), 0, 254);\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $toscal8(x: number): number {\n return $clamp($roundTowardZero(x * 127), -127, 127) + 127;\n}\n\n/** @returns An unsigned scalar between 0.0 and 1.0. */\nexport function $fromuscal8(x: number): number {\n // Make symmetric: (0.5 + round((uint8 - 127) / 254 * 100)) / 100\n return $clamp(($roundAwayFromZero((x - 127) * 0.3937007874015748) + 50) * 0.01, 0, 1);\n}\n\n/** @returns A signed scalar between -1.0 and 1.0. */\nexport function $fromscal8(x: number): number {\n // Make symmetric: round((uint8 - 127) / 127 * 100) / 100\n return $clamp($roundAwayFromZero((x - 127) * 0.787401574803149) * 0.01, -1, 1);\n}\n","/**\n * Field types for defining encoding formats.\n *\n * @see [Types](https://github.com/reececomo/tinybuf/blob/main/docs/types.md)\n */\nexport const Type = {\n /**\n * Unsigned integer (1 - 8 bytes).\n * - 0 → 127 = 1 byte\n * - 128 → 16,384 = 2 bytes\n * - 16,385 → 536,870,911 = 4 bytes\n * - 536,870,912 → `Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n UInt: \"uint\",\n\n /** Unsigned 8-bit integer (between 0 and 255, 1 byte). */\n UInt8: \"u8\",\n\n /** Unsigned 16-bit integer (between 0 and 65,535, 2 bytes). */\n UInt16: \"u16\",\n\n /** Unsigned 32-bit integer (between 0 and 4,294,967,295, 4 bytes). */\n UInt32: \"u32\",\n\n /**\n * Signed integer (1 - 8 bytes).\n * - 0 → ±64 = 1 byte\n * - ±65 → ±8,192 = 2 bytes\n * - ±8,193 → ±268,435,456 = 4 bytes\n * - ±268,435,457 → ±`Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n Int: \"int\",\n\n /** Signed 1 byte integer (between -127 and 127). */\n Int8: \"i8\",\n\n /** Signed 2 byte integer (between -32,767 and 32,767). */\n Int16: \"i16\",\n\n /** Signed 4 byte integer (between -2,147,483,647 and 2,147,483,647). */\n Int32: \"i32\",\n\n /** Default JavaScript `number` type. Floating-point number (64-bit, double precision, 8 bytes). */\n Float64: \"f64\",\n\n /** Floating-point number (32-bit, single precision, 4 bytes). */\n Float32: \"f32\",\n\n /**\n * Floating-point number (16-bit in FP16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision; maximum range: ±65,504.\n */\n Float16: \"f16\",\n\n /**\n * Floating-point number (16-bit in BF16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision.\n */\n BFloat16: \"b16\",\n\n /** A signed 2-decimal scalar between -1.00 and 1.00 (1 byte). */\n Scalar8: \"sc\",\n\n /** An unsigned 2-decimal scalar between 0.00 and 1.00 (1 byte). */\n UScalar8: \"usc\",\n\n /**\n * Boolean value (1 byte).\n * @see {Bools} for packing multiple booleans into a single byte.\n */\n Bool: \"bl\",\n\n /** Any array of booleans (1 bit overhead, encoded as UInt). */\n Bools: \"bls\",\n\n /** Any ArrayBuffer or ArrayBufferView (e.g. Uint8Array) value (encoded as 1 x UInt for byte length + buffer bytes). */\n Buffer: \"buf\",\n\n /** A UTF-8 string (encoded as 1 x UInt for UTF-8 byte length + UTF-8 bytes). */\n String: \"str\",\n\n /** Any JSON data (encodes as UTF-8). */\n JSON: \"jsn\",\n\n /** JavaScript RegExp object. */\n RegExp: \"re\",\n\n /**\n * JavaScript Date object.\n *\n * Encoded as an 8 byte (64-bit) integer UTC timestamp from as the number\n * of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).\n *\n * @see {Date}\n */\n Date: \"dt\",\n} as const;\n\nexport type TypeLiteral = typeof Type[keyof typeof Type];\nexport const ValidTypes = Object.values(Type);\n\n/**\n * Mappings for the value types.\n */\nexport type ValueTypes = {\n [Type.Int]: number;\n [Type.Int8]: number;\n [Type.Int16]: number;\n [Type.Int32]: number;\n [Type.UInt]: number;\n [Type.UInt8]: number;\n [Type.UInt16]: number;\n [Type.UInt32]: number;\n [Type.Float64]: number;\n [Type.Float32]: number;\n [Type.Float16]: number;\n [Type.BFloat16]: number;\n [Type.Scalar8]: number;\n [Type.UScalar8]: number;\n [Type.Bool]: boolean;\n [Type.Bools]: boolean[];\n [Type.Buffer]: Uint8Array | ArrayBuffer | ArrayBufferView;\n [Type.String]: string;\n [Type.JSON]: any;\n [Type.RegExp]: RegExp;\n [Type.Date]: Date;\n};\n\n/** https://www.totaltypescript.com/concepts/the-prettify-helper */\ntype Pretty = T extends ArrayBuffer | ArrayBufferView | Date | RegExp | Uint8Array ? T\n : T extends Array ? Array>\n : T extends object ? {[K in keyof T]: Pretty} & unknown : T;\n\n/** @throws any error too */\nexport type ValidationFn = (x: T) => undefined | boolean | Error;\nexport type TransformFn = (x: T) => T;\nexport type Transforms = TransformFn | [preEncode: TransformFn] | [preEncode: TransformFn | undefined, postDecode: TransformFn | undefined];\n\n/**\n * A wrapper around any Type definition that declares it as optional.\n */\nexport class MaybeType {\n public constructor(public type: T) {}\n}\n\n/**\n * Wrap any definition as optional.\n */\nexport function optional(t: T): MaybeType {\n return new MaybeType(t);\n}\n\n/**\n * A definition for an object binary encoder.\n */\nexport type EncoderDefinition = {\n [key: string]: FieldDefinition | MaybeType;\n};\n\n/**\n * Definition for an object-field binary encoder.\n */\nexport type FieldDefinition = keyof ValueTypes | [keyof ValueTypes] | EncoderDefinition | [EncoderDefinition] | MaybeType;\n\n/**\n * The resulting type of the decoded data, based on the encoder definition.\n */\ntype RawDecodedType = {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? never : EKey]: EncoderType[EKey] extends keyof ValueTypes\n ? ValueTypes[EncoderType[EKey]]\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Array\n : EncoderType[EKey] extends EncoderDefinition\n ? RawDecodedType\n : EncoderType[EKey] extends [EncoderDefinition]\n ? Array>\n : never;\n} & {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? EKey : never]?: EncoderType[EKey] extends MaybeType\n ? ValueTypes[OptionalValue] | undefined\n : EncoderType[EKey] extends MaybeType\n ? Array | undefined\n : EncoderType[EKey] extends MaybeType\n ? RawDecodedType | undefined\n : never;\n};\n\nexport type DecodedType = Pretty>;\n\nexport type TransformConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? Transforms\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Transforms\n : EncoderType[EKey] extends EncoderDefinition\n ? TransformConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? TransformConfig\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? TransformConfig | undefined\n : never;\n};\n\nexport type ValidationConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? ValidationFn\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? ValidationFn\n : EncoderType[EKey] extends EncoderDefinition\n ? ValidationConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? ValidationConfig\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationConfig | undefined\n : never;\n};\n","/**\n * Mask booleans to a uint32.\n *\n * @param x - A boolean array.\n * @param padBit - A bit to pad the mask (for variable length data).\n */\nexport const mask = (x: boolean[], padBit: 0 | 1 = 0b1): number => {\n return x.reduce((n, b: any) => (n << 1) | b, padBit);\n};\n\n/**\n * Unmask booleans from a uint32.\n *\n * @param x - A uint32 number.\n * @param l - number of booleans to expect (default: infer lenth from x where x is encoded with a pad bit)\n * or pass an existing boolean array to decode in-place.\n */\nexport const unmask = (x: number, l?: number | boolean[]): boolean[] => {\n const len = l === undefined ? 31 - Math.clz32(x) : Array.isArray(l) ? l.length : l;\n const val = Array.isArray(l) && l.length === len ? l : new Array(len);\n for (let i = 0; i < len; i++) val[i] = !!(x & (1 << (len - 1 - i)));\n return val;\n};\n","export const $utf8encode = (function () {\n const encoder = new TextEncoder();\n return (x?: string): Uint8Array => encoder.encode(x);\n})();\n\nexport const $utf8decode = (function () {\n const decoder = new TextDecoder(\"utf-8\");\n return (y: Uint8Array): string => decoder.decode(y);\n})();\n","/**\n * Returns the nearest half precision float representation of a number.\n * @param x A numeric expression.\n */\nexport function f16round(x: number): number {\n return $fromf16($tof16(x));\n}\n\n/**\n * Returns the nearest half precision float representation of a number as a 16-bit bitmask.\n */\nexport const $tof16 = (function() {\n const x = new Float32Array(1);\n const y = new Int32Array(x.buffer);\n\n return function (f: number) {\n x[0] = f;\n let i = y[0]; // 32-bit int\n let s = (i >> 16) & 0X8000; // sign\n let z = (i & 0X7FFFFFFF) + 0X1000 | 0;\n\n if (z >= 0X47800000) {\n if ((i & 0X7FFFFFFF) < 0X47800000) return s | 0X7BFF;\n if (z < 0X7F800000) return s | 0X7C00;\n return s | 0X7C00 | (i & 0X007FFFFF) >> 13;\n }\n if (z >= 0X38800000) return s | z - 0X38000000 >> 13;\n else if (z < 0X33000000) return s;\n z = (i & 0X7FFFFFFF) >> 23;\n return s | ((i & 0X7FFFFF | 0X800000)\n + (0X800000 >>> z - 102)\n >> 126 - z);\n };\n}());\n\n/**\n * Returns the nearest half precision float value for a 16-bit bitmask.\n */\nexport const $fromf16 = (function() {\n const z = Math.pow(2, -24); // subnormal constant\n const d = new Float32Array(32 + 1024);\n for (let e = 0; e < 32; e++) d[e] = Math.pow(2, e - 15); // biased exponents\n for (let m = 0; m < 1024; m++) d[m + 0x20] = 1 + m / 1024; // normalized offset mantissas\n\n return function (b: number): number {\n const s = (b & 32768) === 32768 ? -1 : 1; // sign: 1 bit\n const e = b & 31744; // exponent: 5 bits\n const m = b & 1023; // mantissa: 10 bits\n\n if (e === 0) return m === 0 ? s * 0 : s * z;\n if (e === 31744) return m === 0 ? s * Infinity : NaN;\n return d[e >> 10] * d[m + 0x20] * s;\n };\n}());\n","const i = new Uint32Array(1);\nconst f = new Float32Array(i.buffer);\n\n/**\n * Returns the nearest bfloat16 representation of a number.\n * @param x A numeric expression.\n */\nexport function bf16round(x: number): number {\n f[0] = x;\n i[0] = i[0] & 0xFFFF0000;\n return f[0];\n}\n\n/** Returns a 16-bit bfloat16 bitmask for a given float. */\nexport function $tobf16(x: number): number {\n f[0] = x;\n return i[0] >>> 16;\n}\n\n/** Returns the nearest value from a 16-bit bfloat16 bitmask. */\nexport function $frombf16(x: number): number {\n i[0] = x << 16;\n return f[0];\n}\n","import { BufferWriter } from \"./BufferWriter\";\nimport { BufferReader } from \"./BufferReader\";\nimport {\n $fromuscal8,\n $fromscal8,\n $touscal8,\n $toscal8\n} from \"./scalar\";\nimport { TypeLiteral, Type } from \"../Type\";\nimport { mask, unmask } from \"./bitmask\";\nimport { $utf8decode, $utf8encode } from \"./utf8\";\nimport { $floor } from \"./math\";\nimport { $fromf16, $tof16 } from \"./float16\";\nimport { $frombf16, $tobf16 } from \"./bfloat16\";\n\n// Pre-calculated constants\nconst MAX_VARUINT8 = 128,\n MAX_VARUINT16 = 16_384,\n MAX_VARUINT32 = 536_870_912,\n MAX_VARINT8 = 64,\n MAX_VARINT16 = 8_192,\n MAX_VARINT32 = 268_435_456,\n POW_32 = 0x100000000;\n\ntype WriterFn = (value: W, writer: BufferWriter) => void;\ntype ReaderFn = (reader: BufferReader, overwrite?: Partial) => R;\n\nexport interface BinaryTypeCoder {\n $write: WriterFn;\n $read: ReaderFn;\n}\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const uintCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value < 0) value = 0;\n if (value < MAX_VARUINT8) writer.$writeUint8(value);\n else if (value < MAX_VARUINT16) writer.$writeUint16(value + 0x8000);\n else if (value < MAX_VARUINT32) writer.$writeUint32(value + 0xc0000000);\n else if (value >= MAX_VARUINT32) {\n writer.$writeUint32($floor(value / POW_32) + 0xe0000000);\n writer.$writeUint32(value >>> 0);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 1 : 0);\n }\n },\n $read: (reader) => {\n const firstByte = reader.$peek();\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return firstByte;\n }\n else if (!(firstByte & 0x40)) {\n return reader.$readUint16() - 0x8000;\n }\n else if (!(firstByte & 0x20)) {\n return reader.$readUint32() - 0xc0000000;\n }\n\n return (reader.$readUint32() - 0xe0000000) * POW_32\n + reader.$readUint32();\n }\n};\n\nexport const uint8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value),\n $read: (reader) => reader.$readUint8(),\n};\n\nexport const uint16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16(value),\n $read: (reader) => reader.$readUint16(),\n};\n\nexport const uint32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint32(value),\n $read: (reader) => reader.$readUint32(),\n};\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const intCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value >= -MAX_VARINT8 && value < MAX_VARINT8) writer.$writeUint8(value & 0x7f);\n else if (value >= -MAX_VARINT16 && value < MAX_VARINT16) writer.$writeUint16((value & 0x3fff) + 0x8000);\n else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) + 0xc0000000);\n else if (value < -MAX_VARINT32 || value >= MAX_VARINT32) {\n // Split in two 32b uints\n writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) + 0xe0000000);\n writer.$writeUint32(value >>> 0);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 0x7f : 0);\n }\n },\n $read: (reader) => {\n let firstByte = reader.$peek(), i: number;\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return (firstByte & 0x40) ? (firstByte | 0xffffff80) : firstByte;\n }\n else if (!(firstByte & 0x40)) {\n i = reader.$readUint16() - 0x8000;\n return (i & 0x2000) ? (i | 0xffffc000) : i;\n }\n else if (!(firstByte & 0x20)) {\n i = reader.$readUint32() - 0xc0000000;\n return (i & 0x10000000) ? (i | 0xe0000000) : i;\n }\n else {\n i = reader.$readUint32() - 0xe0000000;\n i = (i & 0x10000000) ? (i | 0xe0000000) : i;\n return i * POW_32 + reader.$readUint32();\n }\n }\n};\n\nexport const int8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt8(value),\n $read: (reader) => reader.$readInt8(),\n};\n\nexport const int16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt16(value),\n $read: (reader) => reader.$readInt16(),\n};\n\nexport const int32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt32(value),\n $read: (reader) => reader.$readInt32(),\n};\n\nexport const bfloat16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tobf16(value)),\n $read: (reader) => $frombf16(reader.$readUint16()),\n};\n\nexport const float16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tof16(value)),\n $read: (reader) => $fromf16(reader.$readUint16()),\n};\n\nexport const float32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat32(value),\n $read: (reader) => reader.$readFloat32(),\n};\n\nexport const float64Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat64(value),\n $read: (reader) => reader.$readFloat64(),\n};\n\nexport const uscalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($touscal8(value)),\n $read: (reader) => $fromuscal8(reader.$readUint8()),\n};\n\nexport const scalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($toscal8(value)),\n $read: (reader) => $fromscal8(reader.$readUint8()),\n};\n\nexport const dateCoder: BinaryTypeCoder = {\n $write: (value, writer) => intCoder.$write(value.getTime(), writer),\n $read: (reader) => new Date(intCoder.$read(reader)),\n};\n\nexport const bufferCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n uintCoder.$write(value.byteLength, writer); // prefix length\n writer.$writeBytes(value);\n },\n $read: (reader) => reader.$readBytes(uintCoder.$read(reader)),\n};\n\nexport const stringCoder: BinaryTypeCoder = {\n $write: (value, writer) => bufferCoder.$write($utf8encode(value), writer),\n $read: (reader) => $utf8decode(bufferCoder.$read(reader)),\n};\n\nexport const boolCoder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value ? 1 : 0),\n $read: (reader) => reader.$readUint8() !== 0,\n};\n\nexport const boolsCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (value.length > 28) value = value.slice(0, 28); // drop additional\n uintCoder.$write(mask(value), writer);\n },\n $read: (reader, p) => unmask(uintCoder.$read(reader), p),\n};\n\nexport const jsonCoder: BinaryTypeCoder = {\n $write: (value, writer) => stringCoder.$write(JSON.stringify(value), writer),\n $read: (reader) => JSON.parse(stringCoder.$read(reader)),\n};\n\nexport const regexCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n writer.$writeUint8(mask([value.global, value.ignoreCase, value.multiline]));\n stringCoder.$write(value.source, writer);\n },\n $read: (reader) => {\n const [g, i, m] = unmask(reader.$readUint8());\n return new RegExp(stringCoder.$read(reader), (g ? \"g\" : \"\") + (i ? \"i\" : \"\") + (m ? \"m\" : \"\"));\n }\n};\n\nexport const writers: Record> = {\n [Type.UInt]: uintCoder.$write,\n [Type.UInt8]: uint8Coder.$write,\n [Type.UInt16]: uint16Coder.$write,\n [Type.UInt32]: uint32Coder.$write,\n [Type.Int]: intCoder.$write,\n [Type.Int8]: int8Coder.$write,\n [Type.Int16]: int16Coder.$write,\n [Type.Int32]: int32Coder.$write,\n [Type.Float64]: float64Coder.$write,\n [Type.Float32]: float32Coder.$write,\n [Type.Float16]: float16Coder.$write,\n [Type.BFloat16]: bfloat16Coder.$write,\n [Type.Scalar8]: scalar8Coder.$write,\n [Type.UScalar8]: uscalar8Coder.$write,\n [Type.Bool]: boolCoder.$write,\n [Type.Bools]: boolsCoder.$write,\n [Type.Buffer]: bufferCoder.$write,\n [Type.String]: stringCoder.$write,\n [Type.JSON]: jsonCoder.$write,\n [Type.RegExp]: regexCoder.$write,\n [Type.Date]: dateCoder.$write,\n};\n\nexport const readers: Record> = {\n [Type.UInt]: uintCoder.$read,\n [Type.UInt8]: uint8Coder.$read,\n [Type.UInt16]: uint16Coder.$read,\n [Type.UInt32]: uint32Coder.$read,\n [Type.Int]: intCoder.$read,\n [Type.Int8]: int8Coder.$read,\n [Type.Int16]: int16Coder.$read,\n [Type.Int32]: int32Coder.$read,\n [Type.Float64]: float64Coder.$read,\n [Type.Float32]: float32Coder.$read,\n [Type.Float16]: float16Coder.$read,\n [Type.BFloat16]: bfloat16Coder.$read,\n [Type.Scalar8]: scalar8Coder.$read,\n [Type.UScalar8]: uscalar8Coder.$read,\n [Type.Bool]: boolCoder.$read,\n [Type.Bools]: boolsCoder.$read,\n [Type.Buffer]: bufferCoder.$read,\n [Type.String]: stringCoder.$read,\n [Type.JSON]: jsonCoder.$read,\n [Type.RegExp]: regexCoder.$read,\n [Type.Date]: dateCoder.$read,\n};\n","/** Default maximum transmission unit in networking */\nconst MTU = 1500;\n\n/** Set Tinybuf global config */\nexport const setTinybufConfig = (c: Partial): void => {\n cfg = { ...cfg, ...c };\n};\n\nexport type TinybufConfig = {\n /**\n * (default: false)\n *\n * This sets the default value for `preserveBytes` on\n * `encode(data, preserveBytes?)`.\n *\n * By default, `encode()` returns its encoded bytes as a `Uint8Array`\n * view of the bytes in the shared encoding buffer.\n *\n * This is suitable for synchronous use (e.g. high-performance applications)\n * as it avoids slow and expensive memory allocation and fragmentation on\n * each call to `encode()`.\n *\n * However, susbsequent calls are destructive to the underlying bytes, so\n * for asynchronous uses (e.g. Promises, Workers, long-lived storage), set\n * `preserveBytes` to `true`.\n */\n safe: boolean,\n\n /**\n * (default: true)\n * By default, format encoders share a global encoding buffer for performance\n * and memory management reasons.\n *\n * When set to false, each format is allocated an individual encoding buffer.\n *\n * Enable to maximise performance and memory re-use, just be cautious of\n * possible race conditions.\n */\n useGlobalEncodingBuffer: boolean,\n\n /**\n * (default: 1500)\n * The maximum bytes that can be allocated to an encoding buffer.\n *\n * Default is 1500 bytes, the standard \"Maximum Transmission Unit\".\n */\n encodingBufferMaxSize: number,\n\n /**\n * (default: 256)\n * Initial bytes to allocate for an encoding buffer.\n */\n encodingBufferInitialSize: number,\n\n /**\n * (default: 256)\n * Additional bytes to allocated when dynamically increasing the size of an encoding buffer.\n */\n encodingBufferIncrement: number,\n};\n\n/** @internal */\nexport let cfg: TinybufConfig = {\n safe: false,\n useGlobalEncodingBuffer: true,\n encodingBufferMaxSize: MTU,\n encodingBufferInitialSize: 256,\n encodingBufferIncrement: 256,\n};\n","import { cfg } from \"../config\";\nimport { TinybufError } from \"./errors\";\n\n/**\n * Wraps a buffer with a write head pointer.\n *\n * @internal\n */\nexport class BufferWriter {\n public $byteLength: number = 0;\n private _$dataView: DataView;\n private _$bytes: Uint8Array;\n private _$base: number;\n private _$writeHead: number = 0;\n private _$resizable: boolean;\n\n public constructor($0: number | Uint8Array) {\n this._$resizable = typeof $0 === \"number\";\n let b = $0 instanceof Uint8Array ? $0 : new Uint8Array($0);\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$dataView = new DataView(b.buffer);\n }\n\n /** Retarget the writer to a fixed-size byte array, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array): this {\n if (this._$dataView.buffer !== b.buffer) {\n this._$dataView = new DataView(b.buffer);\n }\n\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$resizable = false;\n this._$writeHead = 0;\n this.$byteLength = 0;\n\n return this;\n }\n\n public $viewBytes(): Uint8Array {\n return this._$bytes.subarray(0, this.$byteLength);\n }\n\n public $copyBytes(): Uint8Array {\n const buf = new Uint8Array(this.$byteLength);\n buf.set(this.$viewBytes());\n return buf;\n }\n\n // ----- Writers: -----\n\n public $writeInt8(value: number): void {\n this._$pre(1).setInt8(this._$writeHead, value);\n }\n\n public $writeInt16(value: number): void {\n this._$pre(2).setInt16(this._$writeHead, value, true);\n }\n\n public $writeInt32(value: number): void {\n this._$pre(4).setInt32(this._$writeHead, value, true);\n }\n\n public $writeUint8(value: number): void {\n this._$pre(1).setUint8(this._$writeHead, value);\n }\n\n public $writeUint16(value: number): void {\n this._$pre(2).setUint16(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeUint32(value: number): void {\n this._$pre(4).setUint32(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeFloat32(value: number): void {\n this._$pre(4).setFloat32(this._$writeHead, value, true);\n }\n\n public $writeFloat64(value: number): void {\n this._$pre(8).setFloat64(this._$writeHead, value, true);\n }\n\n public $writeBytes(b: Uint8Array | ArrayBuffer | ArrayBufferView): void {\n // allocate bytes first\n this._$pre(b.byteLength);\n\n this._$bytes.set(\n b instanceof Uint8Array\n ? b\n : ArrayBuffer.isView(b)\n ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n : new Uint8Array(b),\n this._$writeHead - this._$base\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Pre-allocate some bytes on the dataview, moving the write head into\n * position.\n *\n * @throws TinybufError\n */\n private _$pre(bytes: number): DataView {\n if (this.$byteLength + bytes > this._$bytes.byteLength) {\n this._$malloc(bytes);\n }\n\n this._$writeHead = this._$base + this.$byteLength;\n this.$byteLength += bytes;\n\n return this._$dataView;\n }\n\n /**\n * @throws TinybufError\n */\n private _$malloc(bytes: number): void {\n if (!this._$resizable) {\n throw new TinybufError(\"exceeded buffer length: \" + this._$bytes.byteLength);\n }\n\n const currentBytes = this._$bytes.byteLength;\n const minNewBytes = this.$byteLength + bytes - currentBytes;\n const availableBytes = cfg.encodingBufferMaxSize - currentBytes;\n\n if (minNewBytes > availableBytes) {\n throw new TinybufError(\"exceeded encodingBufferMaxSize: \" + cfg.encodingBufferMaxSize);\n }\n\n const increment = cfg.encodingBufferIncrement;\n const newBytes = Math.ceil(minNewBytes / increment) * increment;\n const newSize = currentBytes + Math.min(newBytes, availableBytes);\n const buf = new Uint8Array(newSize);\n\n // copy bytes\n buf.set(this._$bytes);\n\n // update refs\n this._$dataView = new DataView(buf.buffer);\n this._$bytes = buf;\n this._$base = 0;\n }\n}\n","/**\n * Wraps a buffer with a read head pointer.\n *\n * @internal\n */\nexport class BufferReader {\n public i: number;\n private _$dataView!: DataView;\n private _$base!: number;\n private _$byteLength!: number;\n\n public constructor(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number) {\n this.$reset(b, headerBytes);\n }\n\n /** Retarget the reader to a new buffer, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number): this {\n const isView = ArrayBuffer.isView(b);\n const buffer = isView ? b.buffer : b;\n const offset = isView ? b.byteOffset : 0;\n let dv = this._$dataView;\n\n if (\n dv === undefined\n || dv.buffer !== buffer\n || offset < dv.byteOffset\n || offset + b.byteLength > dv.byteOffset + dv.byteLength\n ) {\n dv = this._$dataView = b instanceof DataView ? b : new DataView(buffer);\n }\n\n this._$base = offset - dv.byteOffset;\n this._$byteLength = b.byteLength;\n this.i = headerBytes ?? 0; // internal offset (header)\n\n return this;\n }\n\n /** Read the next byte, without moving the read head pointer. */\n public $peek(): number {\n if (this.i >= this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n return this._$dataView.getUint8(this._$base + this.i);\n }\n\n /** Skip the next byte without reading it. */\n public $skip(): void {\n this.i++;\n }\n\n // ----- Readers: -----\n\n public $readUint8(): number {\n return this._$dataView.getUint8(this._$at(1));\n }\n\n public $readUint16(): number {\n return this._$dataView.getUint16(this._$at(2)); // big-endian\n }\n\n public $readUint32(): number {\n return this._$dataView.getUint32(this._$at(4)); // big-endian\n }\n\n public $readInt8(): number {\n return this._$dataView.getInt8(this._$at(1));\n }\n\n public $readInt16(): number {\n return this._$dataView.getInt16(this._$at(2), true); // little-endian\n }\n\n public $readInt32(): number {\n return this._$dataView.getInt32(this._$at(4), true); // little-endian\n }\n\n public $readFloat32(): number {\n return this._$dataView.getFloat32(this._$at(4), true); // little-endian\n }\n\n public $readFloat64(): number {\n return this._$dataView.getFloat64(this._$at(8), true); // little-endian\n }\n\n /** @throws RangeError if exceeds length */\n public $readBytes(bytes: number): Uint8Array {\n return new Uint8Array(\n this._$dataView.buffer,\n this._$dataView.byteOffset + this._$at(bytes),\n bytes\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Advance the read head, returning the DataView offset to read from.\n *\n * @throws RangeError if exceeds length\n */\n private _$at(bytes: number): number {\n const i = this.i;\n\n if (i + bytes > this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n this.i = i + bytes;\n\n return this._$base + i;\n }\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { writers, readers } from \"./lib/coders\";\nimport * as coders from \"./lib/coders\";\nimport { $hashCode, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader, peekHeaderStr } from \"./lib/peek\";\nimport { BufferWriter } from \"./lib/BufferWriter\";\nimport { BufferReader } from \"./lib/BufferReader\";\nimport {\n DecodedType,\n EncoderDefinition,\n FieldDefinition,\n TransformConfig,\n ValidationConfig,\n MaybeType,\n Transforms,\n TypeLiteral,\n ValidationFn,\n ValidTypes,\n} from \"./Type\";\nimport { cfg } from \"./config\";\n\nexport type FormatHeader = string | number;\n\n/**\n * Utility to get the decoded type of a buffer format\n * @example type Format = Decoded\n */\nexport type Decoded = TBufferFormat extends BufferFormat\n ? DecodedType\n : never;\n\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(def: T): BufferFormat;\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(h: HeaderType | null, def: T): BufferFormat;\nexport function defineFormat(a?: HeaderType | T, b?: T): BufferFormat {\n return a !== null && typeof a === \"object\"\n ? new BufferFormat(a as T)\n : new BufferFormat(b as T, a as HeaderType);\n}\n\nfunction isValidHeader(h: FormatHeader): boolean {\n if (typeof h === \"number\") return Number.isInteger(h) && h >= 0 && h <= 65_535;\n if (typeof h === \"string\") return new TextEncoder().encode(h).byteLength === 2;\n return false;\n}\n\n/**\n * BufferFormat is a utility class for encoding and decoding binary data based\n * on a provided encoding format.\n *\n * @see {header}\n * @see {encode(data)}\n * @see {decode(binary)}\n */\nexport class BufferFormat {\n /** @internal */\n private static _$globalWriter?: BufferWriter;\n\n /**\n * A unique identifier encoded as the first 2 bytes (or `undefined` if headerless).\n *\n * @see {peekHeader(...)}\n * @see {peekHeaderStr(...)}\n */\n public header!: HeaderType;\n\n /** @internal */\n private _$header!: number; // always uint16 vesion\n /** @internal */\n private _$type!: TypeLiteral;\n /** @internal */\n private _$fields!: Field[];\n /** @internal */\n private _$fieldsMap!: Map;\n\n /** @internal */\n private _$format?: string;\n /** @internal */\n private _$transforms?: Transforms | undefined;\n /** @internal */\n private _$validate?: ValidationFn | undefined;\n /** @internal */\n private _$hasValidationOrTransforms = false;\n /** @internal */\n private _$writer?: BufferWriter;\n /** @internal */\n private _$intoWriter?: BufferWriter;\n /** @internal */\n private _$reader?: BufferReader;\n\n public constructor(\n def: EncoderType,\n header?: HeaderType | null,\n ) {\n // set definition\n if (typeof def === \"string\" && ValidTypes.includes(def)) {\n this._$type = def;\n }\n else if (def instanceof MaybeType) {\n throw new TypeError(\"Format cannot be optional\");\n }\n else if (def instanceof Object) {\n this._$type = undefined; // object\n this._$fieldsMap = new Map();\n this._$fields = Object.keys(def).map((name) => {\n const f = new Field(name, def[name]);\n this._$fieldsMap.set(name, f); // also set map entry\n return f;\n });\n\n // set headers\n if (header === undefined) {\n this.header = $hashCode(this.f) as HeaderType; // automatic\n this._$header = this.header as number;\n }\n else if (header === null) {\n this.header = undefined; // headerless\n this._$header = undefined;\n }\n else if (isValidHeader(header)) {\n this.header = header; // manual\n this._$header = typeof header === \"number\" ? header : $strToHashCode(header);\n }\n else {\n throw new TypeError(\"Header must be 2-byte string, uint16, or null.\");\n }\n }\n else {\n throw new TypeError(\"Format must be object or Type\");\n }\n }\n\n // ----- Static methods: -----\n\n /**\n * Read the header of a buffer as a number.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeader = peekHeader;\n\n /**\n * Read the header of a buffer as a string.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeaderStr = peekHeaderStr;\n\n // ----- Accessors: -----\n\n /**\n * @example \"{uint8,str[]?}\"\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private get f(): string {\n if (this._$format === undefined) {\n this._$format = this._$fields !== undefined\n ? `{${this._$fields.map(v => v.f).join(\",\")}}`\n : `${this._$type}`;\n }\n\n return this._$format;\n }\n\n /** @internal */\n private static _$initWriter(): BufferWriter {\n if (cfg.useGlobalEncodingBuffer) {\n if (!BufferFormat._$globalWriter) {\n this._$globalWriter = new BufferWriter(cfg.encodingBufferMaxSize);\n }\n\n return this._$globalWriter;\n }\n\n return new BufferWriter(cfg.encodingBufferInitialSize);\n }\n\n /**\n * Encode an object into an existing byte array.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n */\n public encodeInto>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): Uint8Array {\n return bytes.subarray(0, this.encodeIntoLength(data, bytes));\n }\n\n /**\n * Encode an object into an existing byte array, without allocating a view.\n *\n * @returns the number of bytes written to the start of `bytes`\n * @throws if fails to encode value to schema, or `bytes` is too small\n */\n public encodeIntoLength>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): number {\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n const writer = this._$intoWriter?.$reset(bytes) ?? new BufferWriter(bytes);\n this._$intoWriter = undefined;\n\n try {\n this._$write(data, writer);\n\n return writer.$byteLength;\n }\n finally {\n this._$intoWriter = writer;\n }\n }\n\n /**\n * Encode an object to bytes.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n *\n * @param data - data to encode\n * @param preserveBytes - (default: `setTinybufConfig().safe`) When set to true, copies encoded\n * bytes to a new buffer. When set to false, returns an unsafe view of bytes but prevents\n * unnnecessary memory allocation and fragmentation.\n *\n * @returns a copy of encoded bytes\n * @throws if fails to encode value to schema\n */\n public encode>(\n data: TDecodedType,\n preserveBytes?: boolean,\n ): Uint8Array {\n if (!this._$writer) {\n // lazy init\n this._$writer = BufferFormat._$initWriter();\n }\n\n // reset\n this._$writer.$byteLength = 0;\n\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n this._$write(data, this._$writer);\n\n return (preserveBytes ?? cfg.safe)\n ? this._$writer.$copyBytes()\n : this._$writer.$viewBytes();\n }\n\n /**\n * Decode binary data into an existing object instance.\n * @throws if fails to decode bytes to schema.\n */\n public decodeInto>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial,\n ): TDecodedType {\n return this._$decode(bytes, obj);\n }\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer\n ): TDecodedType;\n /**\n * @deprecated use decodeInto() instead\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto: Partial,\n ): TDecodedType;\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto?: Partial | undefined,\n ): TDecodedType {\n return this._$decode(bytes, decodeInto);\n }\n\n /**\n * Set additional transform functions to apply before encoding and after decoding.\n */\n public setTransforms(transforms: TransformConfig | Transforms): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof transforms === \"function\" || (Array.isArray(transforms) && typeof transforms[0] === \"function\")) {\n this._$transforms = transforms;\n }\n else {\n for (const name of Object.keys(transforms)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set transforms for field '${name}'`);\n }\n\n // Set validation for object.\n field.$coder.setTransforms(transforms[name]);\n }\n }\n\n return this;\n }\n\n /**\n * Set additional validation rules which are applied on encode() and decode().\n *\n * - Validation functions should throw an error, return an error, or return boolean false.\n * - Anything else is treated as successfully passing validation.\n */\n public setValidation(validations: ValidationConfig | ValidationFn): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof validations === \"function\") {\n this._$validate = validations;\n }\n else {\n for (const name of Object.keys(validations)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set validation function for field '${name}'`);\n }\n\n field.$coder.setValidation(validations[name]);\n }\n }\n\n return this;\n }\n\n // ----- Implementation: -----\n\n /** @internal */\n private _$decode(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial | undefined,\n ): TDecodedType {\n const headerBytes = this.header === undefined ? 0 : 2;\n\n const reader = this._$reader?.$reset(bytes, headerBytes) ?? new BufferReader(bytes, headerBytes);\n this._$reader = undefined;\n\n try {\n return this._$read(reader, obj);\n }\n finally {\n this._$reader = reader;\n }\n }\n\n /**\n * @param value\n * @param bw\n * @throws if the value is invalid\n *\n * @internal\n */\n private _$write(value: any, bw: BufferWriter): void {\n // write header\n if (this._$header !== undefined) bw.$writeUint16(this._$header);\n\n // write scalar\n if (this._$type !== undefined) {\n const safeValue = (this._$validate || this._$transforms) ? this._$preprocess(value) : value;\n\n return writers[this._$type](safeValue, bw);\n }\n\n // check for object type\n if (typeof value !== \"object\" || !value) {\n throw new TypeError(\"expected object type\");\n }\n\n // write each field\n for (const field of this._$fields) {\n const subValue = value[field.$name];\n\n if (field.$isOptional) {\n if (subValue === undefined || subValue === null) {\n coders.boolCoder.$write(false, bw);\n continue; // skip\n }\n else {\n coders.boolCoder.$write(true, bw);\n }\n }\n else if (subValue == null) {\n throw new Error(`missing required value: ${field.$name}`);\n }\n\n if (field.$isArray) {\n // array\n this._$writeArray(subValue, bw, field.$coder);\n continue;\n }\n\n // scalar/object field\n field.$coder._$write(subValue, bw);\n }\n }\n\n /**\n * pre-process: validation and/or transforms\n * @internal\n */\n private _$preprocess>(data: T): T {\n if (this._$validate) this._$processValidation(data);\n\n if (typeof this._$transforms === \"function\") {\n return this._$transforms(data);\n }\n else if (Array.isArray(this._$transforms) && typeof this._$transforms[0] === \"function\") {\n return this._$transforms[0](data);\n }\n\n return data;\n }\n\n /**\n * post-process: validation and/or transforms\n * @internal\n */\n private _$postprocess>(data: T): T {\n if (Array.isArray(this._$transforms) && typeof this._$transforms[1] === \"function\") {\n data = this._$transforms[1](data);\n }\n\n if (this._$validate) this._$processValidation(data);\n\n return data;\n }\n\n private _$processValidation(data: any): void {\n if (!this._$validate) return;\n const res = this._$validate(data);\n if (res instanceof Error) throw res;\n if (res === false) throw new Error(\"failed validation\");\n }\n\n /**\n * This function will be executed only the first time\n * After that, we'll compile the read routine and add it directly to the instance\n * @param state\n * @returns\n * @throws if fails\n *\n * @internal\n */\n private _$read>(state: BufferReader, obj?: Partial): TDecodedType {\n // This function will be executed only the first time to compile the read routine.\n // After that, we'll compile the read routine and add it directly to the instance\n\n // Update the read method implementation.\n this._$read = this._$compileFormatReadFn();\n\n return this._$read(state, obj);\n }\n\n /**\n * Generate read function code for this coder.\n *\n * @example\n * let v=o??{};\n * v.prop1=this._$readField(0,s,o);\n * v.prop2=this._$readField(1,s,o);\n * return v\n *\n * @internal\n */\n private _$makeObjectReadFnBody(): string {\n const fieldsStr: string = this._$fields\n .map(({ $name: n }, i) => `v.${n}=this.${this._$readField.name}(${i},s,v.${n})`)\n .join(\";\");\n\n return `let v=o??{};${fieldsStr};return v;`;\n }\n\n /**\n * Read an individual field.\n * @internal\n */\n private _$readField(fieldIndex: number, state: BufferReader, obj?: any): any {\n const field = this._$fields[fieldIndex];\n\n if (field.$isOptional && !coders.boolCoder.$read(state)) {\n return undefined;\n }\n\n if (field.$isArray) {\n return this._$readArray(field.$coder, state, obj);\n }\n\n return field.$coder._$read(state, obj);\n }\n\n /**\n * Compile the decode() method for this object.\n *\n * @internal\n */\n private _$compileFormatReadFn>(): (state: BufferReader, obj: Partial | undefined) => TDecodedType {\n if (this._$type !== undefined) {\n // scalar type\n return this._$hasValidationOrTransforms\n ? (s) => this._$postprocess(readers[this._$type](s))\n : readers[this._$type];\n }\n\n // object type\n return new Function(\"s\", \"o\", this._$makeObjectReadFnBody()) as any;\n }\n\n /**\n * @internal\n */\n private _$writeArray(value: any[], bw: BufferWriter, type: BufferFormat): void {\n if (!Array.isArray(value)) {\n throw new TypeError(`expected array, instead got: ${value}`);\n }\n\n coders.uintCoder.$write(value.length, bw);\n for (let i = 0; i < value.length; i++) {\n type._$write(value[i], bw);\n }\n }\n\n /**\n * @throws if invalid data\n * @internal\n */\n private _$readArray(type: BufferFormat, state: any, obj?: Array): Array {\n const len = coders.uintCoder.$read(state);\n const arr = Array.isArray(obj) ? obj : new Array(len);\n if (arr.length !== len) arr.length = len;\n for (let j = 0; j < arr.length; j++) {\n arr[j] = type._$read(state, obj?.[j]);\n }\n return arr;\n }\n}\n\n/**\n * Parses and represents an object field.\n *\n * @internal\n */\nclass Field {\n public $name: string;\n public $coder: BufferFormat;\n public $isOptional: boolean;\n public $isArray: boolean;\n\n private _$formatString?: string;\n\n public constructor(name: string, rawType: FieldDefinition) {\n this.$isOptional = rawType instanceof MaybeType;\n let type = rawType instanceof MaybeType ? rawType.type : rawType;\n\n this.$name = name;\n\n if (Array.isArray(type)) {\n if (type.length !== 1) {\n throw new TypeError(\"Array type must contain exactly one format\");\n }\n\n type = type[0];\n this.$isArray = true;\n }\n else {\n this.$isArray = false;\n }\n\n this.$coder = new BufferFormat(type, null);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public get f(): string {\n if (this._$formatString === undefined) {\n this._$formatString = `${(this.$coder as any).f}${this.$isArray ? \"[]\" : \"\"}${this.$isOptional ? \"?\" : \"\"}`;\n }\n\n return this._$formatString;\n }\n}\n"],"names":["TinybufError","Error","$hashCode","str","hash","i","length","charCodeAt","$strToHashCode","$hashCodeToStr","hashCode","String","fromCharCode","Math","floor","peekHeader","b","byteLength","RangeError","Uint8Array","DataView","getUint16","u8","ArrayBuffer","isView","buffer","byteOffset","peekHeaderStr","bufferParser","BufferParser","constructor","this","_$formats","Map","_$data","processBuffer","f","data","cb","r","header","has","get","_a","decode","set","e","err","stack","on","format","callback","decodeInPlace","ignore","forEach","clear","$floor","$ceil","ceil","$clamp","value","min","max","$roundTowardZero","x","$roundAwayFromZero","uscalround","$fromuscal8","$touscal8","scalround","$fromscal8","$toscal8","Type","UInt","UInt8","UInt16","UInt32","Int","Int8","Int16","Int32","Float64","Float32","Float16","BFloat16","Scalar8","UScalar8","Bool","Bools","Buffer","JSON","RegExp","Date","ValidTypes","Object","values","MaybeType","type","optional","t","mask","padBit","reduce","n","unmask","l","len","undefined","clz32","Array","isArray","val","$utf8encode","encoder","TextEncoder","encode","$utf8decode","decoder","TextDecoder","y","f16round","$fromf16","$tof16","Float32Array","Int32Array","s","z","pow","d","m","Infinity","NaN","Uint32Array","bf16round","MAX_VARUINT32","MAX_VARINT32","POW_32","uintCoder","$write","writer","Number","$writeUint8","$writeUint16","$writeUint32","$read","reader","firstByte","$peek","$readUint32","$readUint16","$skip","uint8Coder","$readUint8","uint16Coder","uint32Coder","intCoder","int8Coder","$writeInt8","$readInt8","int16Coder","$writeInt16","$readInt16","int32Coder","$writeInt32","$readInt32","bfloat16Coder","$tobf16","$frombf16","float16Coder","float32Coder","$writeFloat32","$readFloat32","float64Coder","$writeFloat64","$readFloat64","uscalar8Coder","scalar8Coder","dateCoder","getTime","bufferCoder","$writeBytes","$readBytes","stringCoder","boolCoder","boolsCoder","slice","p","jsonCoder","stringify","parse","regexCoder","global","ignoreCase","multiline","source","g","writers","readers","setTinybufConfig","c","cfg","assign","safe","useGlobalEncodingBuffer","encodingBufferMaxSize","encodingBufferInitialSize","encodingBufferIncrement","BufferWriter","$0","$byteLength","_$writeHead","_$resizable","_$bytes","_$base","_$dataView","$reset","$viewBytes","subarray","$copyBytes","buf","_$pre","setInt8","setInt16","setInt32","setUint8","setUint16","setUint32","setFloat32","setFloat64","bytes","_$malloc","currentBytes","minNewBytes","availableBytes","increment","newBytes","newSize","BufferReader","headerBytes","offset","dv","_$byteLength","getUint8","_$at","getUint32","getInt8","getInt16","getInt32","getFloat32","getFloat64","defineFormat","a","BufferFormat","def","_$hasValidationOrTransforms","includes","_$type","TypeError","_$fieldsMap","_$fields","keys","map","name","Field","_$header","isValidHeader","h","isInteger","_$format","v","join","_$initWriter","_$globalWriter","encodeInto","encodeIntoLength","_$preprocess","_b","_$intoWriter","_$write","preserveBytes","_$writer","decodeInto","obj","_$decode","setTransforms","transforms","_$transforms","field","$coder","setValidation","validations","_$validate","_$reader","_$read","bw","safeValue","subValue","$name","$isOptional","coders.boolCoder","$isArray","_$writeArray","_$processValidation","_$postprocess","res","state","_$compileFormatReadFn","_$makeObjectReadFnBody","fieldsStr","_$readField","fieldIndex","_$readArray","Function","coders.uintCoder","arr","j","rawType","_$formatString"],"mappings":"AAEM,MAAOA,qBAAqBC,OCM5B,SAAUC,UAAUC,GACxB,IAAIC,EAAO,KACX,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAC9BD,EAAe,GAAPA,EAAaD,EAAII,WAAWF,GAEtC,OAAc,MAAPD,CACT,CAQM,SAAUI,eAAeL,GAC7B,OAAmB,IAAfA,EAAIG,OAAqBJ,UAAUC,GACZ,IAApBA,EAAII,WAAW,GAAWJ,EAAII,WAAW,EAClD,CAKM,SAAUE,eAAeC,GAC7B,OAAOC,OAAOC,aAAaC,KAAKC,MAAMJ,EAAW,MAAQC,OAAOC,aAAaF,EAAW,IAC1F,CCxBM,SAAUK,WAAWC,GACzB,GAAIA,EAAEC,WAAa,EACjB,MAAM,IAAIC,WAAW,qBAGvB,GAAIF,aAAaG,WAAY,OAAQH,EAAE,IAAM,EAAKA,EAAE,GACpD,GAAIA,aAAaI,SAAU,OAAOJ,EAAEK,UAAU,GAAG,GAEjD,MAAMC,EAAKC,YAAYC,OAAOR,GAAK,IAAIG,WAAWH,EAAES,OAAQT,EAAEU,WAAY,GAAK,IAAIP,WAAWH,EAAG,EAAG,GAEpG,OAAQM,EAAG,IAAM,EAAKA,EAAG,EAC3B,CAOM,SAAUK,cAAcX,GAC5B,OAAOP,eAAeM,WAAWC,GACnC,CCTa,MAAAY,aAAe,IAAoB,IAAIC,mBAEvCA,aAAb,WAAAC,GAEUC,KAAAC,EAAY,IAAIC,IAChBF,KAAAG,EAAS,IAAID,GAsEtB,CA7DQ,aAAAE,CAAcnB,SACnB,IAAIoB,EAAQC,EAAWC,EAAwBC,EAE/C,IACE,MAAMC,EAASzB,WAAWC,GAE1B,IAAKe,KAAKC,EAAUS,IAAID,GACtB,MAAM,IAAIxC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/core/lib/peek.ts","../src/core/BufferParser.ts","../src/core/lib/math.ts","../src/core/lib/scalar.ts","../src/core/Type.ts","../src/core/lib/bitmask.ts","../src/core/lib/utf8.ts","../src/core/lib/float16.ts","../src/core/lib/bfloat16.ts","../src/core/lib/coders.ts","../src/core/config.ts","../src/core/lib/BufferWriter.ts","../src/core/lib/BufferReader.ts","../src/core/BufferFormat.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unified-signatures */\n\nexport class TinybufError extends Error {}\n","/**\n * DJB2 hash algorithm (modified for 16-bit uints).\n *\n * DJB2 is a simple and widely used non-cryptographic\n * hash function created by Daniel J. Bernstein.\n *\n * @returns 16-bit unsigned integer\n */\nexport function $hashCode(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return hash & 0xFFFF; // Ensure the result is a Uint16\n}\n\n/**\n * Returns an unsigned 16-bit integer hashcode for some string.\n * Prefers 2 character string.\n *\n * @returns A UInt16 between 0 and 65535 (inclusive).\n */\nexport function $strToHashCode(str: string): number {\n if (str.length !== 2) return $hashCode(str);\n return str.charCodeAt(0) * 256 + str.charCodeAt(1);\n}\n\n/**\n * Convert a UInt16 hashcode to a 2-byte string.\n */\nexport function $hashCodeToStr(hashCode: number): string {\n return String.fromCharCode(Math.floor(hashCode / 256)) + String.fromCharCode(hashCode % 256);\n}\n","import { $hashCodeToStr } from \"./hashCode\";\n\n\n/**\n * Read the header bytes of a buffer as a number.\n *\n * @throws {RangeError} if buffer size < 2\n */\nexport function peekHeader(b: ArrayBuffer | ArrayBufferView): number {\n if (b.byteLength < 2) {\n throw new RangeError(\"buffer length < 2\");\n }\n\n if (b instanceof Uint8Array) return (b[0] << 8) | b[1];\n if (b instanceof DataView) return b.getUint16(0, false);\n\n const u8 = ArrayBuffer.isView(b) ? new Uint8Array(b.buffer, b.byteOffset, 2) : new Uint8Array(b, 0, 2);\n\n return (u8[0] << 8) | u8[1];\n}\n\n/**\n * Read the header bytes of a buffer as a string.\n *\n * @throws {RangeError} if buffer length < 2\n */\nexport function peekHeaderStr(b: ArrayBuffer | ArrayBufferView): string {\n return $hashCodeToStr(peekHeader(b));\n}\n","import { BufferFormat } from \"./BufferFormat\";\nimport { EncoderDefinition, DecodedType } from \"./Type\";\nimport { TinybufError } from \"./lib/errors\";\nimport { $hashCodeToStr, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader } from \"./lib/peek\";\n\ntype AnyFormat = BufferFormat;\ntype Uint16FormatHeader = number;\n\n/**\n * Small utility for registering and processing format handlers.\n *\n * @example\n * const myHandler = bufferParser()\n * .on(FormatA, aData => {})\n * .on(FormatB, bData => {});\n *\n * myHandler.processBuffer(bytes);\n */\nexport const bufferParser = (): BufferParser => new BufferParser();\n\nexport class BufferParser {\n /** @internal */\n private _$formats = new Map any, decodeInPlace: boolean]>();\n private _$data = new Map(); // used when decoding in-place\n\n /**\n * Decode an array buffer and trigger the relevant data handler.\n *\n * When passed an ArrayBufferView, accesses the underlying 'buffer' instance directly.\n *\n * @throws {TinybufError} if fails to decode, or no handler is registered\n */\n public processBuffer(b: ArrayBuffer | ArrayBufferView): void {\n let f: any, data: any, cb: (data: any) => any, r: boolean;\n\n try {\n const header = peekHeader(b);\n\n if (!this._$formats.has(header)) {\n throw new TinybufError(`Unknown format: ${header} '${$hashCodeToStr(header)}')`);\n }\n\n [f, cb, r] = this._$formats.get(header);\n if (r) data = this._$data.get(header) ?? {};\n data = f.decode(b, data);\n if (r) this._$data.set(header, data);\n }\n catch (e) {\n const err = new TinybufError(`Failed to decode: ${e}`);\n err.stack = e.stack;\n\n throw err;\n }\n\n cb(data);\n }\n\n /**\n * Register a format handler.\n */\n public on>(\n format: BufferFormat,\n callback: (data: TDecodedType) => any,\n {\n decodeInPlace = false,\n } = {},\n ): this {\n if (format.header == null) {\n throw new TinybufError(\"Format requires header\");\n }\n\n const header = typeof format.header === \"string\" ? $strToHashCode(format.header) : format.header;\n\n if (this._$formats.has(header) && this._$formats.get(header)?.[0] !== format) {\n throw new TinybufError(`Format header collision: ${format.header}`);\n }\n\n this._$formats.set(header, [format, callback, decodeInPlace]);\n\n return this;\n }\n\n /** Register a format (or formats) that are recognized. */\n public ignore(...format: AnyFormat[]): this {\n format.forEach(f => this.on(f, () => {}));\n return this;\n }\n\n /** Clears all registered formats and handlers. */\n public clear(): void {\n this._$formats.clear();\n this._$data.clear();\n }\n}\n","export const $floor = Math.floor,\n $ceil = Math.ceil;\n\n/** Clamp a number to a range. */\nexport const $clamp = (value: number, min: number, max: number): number =>\n value > max ? max : value < min ? min : value;\n\n/** Round toward zero */\nexport const $roundTowardZero = (x: number): number => x < 0 ? $ceil(x) : $floor(x);\n\n/** Round away zero */\nexport const $roundAwayFromZero = (x: number): number =>\n x < 0 ? $floor(x) : $ceil(x);\n","import { $clamp, $roundTowardZero, $roundAwayFromZero } from \"./math\";\n\n/**\n * Quantize a number to an 8-bit scalar between 0.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function uscalround(x: number): number {\n return $fromuscal8($touscal8(x));\n}\n\n/**\n * Quantize a number to an 8-bit signed scalar between -1.0 and 1.0.\n *\n * @returns A number (double) in its closest signed scalar representation.\n */\nexport function scalround(x: number): number {\n return $fromscal8($toscal8(x));\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $touscal8(x: number): number {\n return $clamp(127 + $roundTowardZero(x * 254 - 127), 0, 254);\n}\n\n/** @returns A UInt8 bitmask representation. */\nexport function $toscal8(x: number): number {\n return $clamp($roundTowardZero(x * 127), -127, 127) + 127;\n}\n\n/** @returns An unsigned scalar between 0.0 and 1.0. */\nexport function $fromuscal8(x: number): number {\n // Make symmetric: (0.5 + round((uint8 - 127) / 254 * 100)) / 100\n return $clamp(($roundAwayFromZero((x - 127) * 0.3937007874015748) + 50) * 0.01, 0, 1);\n}\n\n/** @returns A signed scalar between -1.0 and 1.0. */\nexport function $fromscal8(x: number): number {\n // Make symmetric: round((uint8 - 127) / 127 * 100) / 100\n return $clamp($roundAwayFromZero((x - 127) * 0.787401574803149) * 0.01, -1, 1);\n}\n","/**\n * Field types for defining encoding formats.\n *\n * @see [Types](https://github.com/reececomo/tinybuf/blob/main/docs/types.md)\n */\nexport const Type = {\n /**\n * Unsigned integer (1 - 8 bytes).\n * - 0 → 127 = 1 byte\n * - 128 → 16,384 = 2 bytes\n * - 16,385 → 536,870,911 = 4 bytes\n * - 536,870,912 → `Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n UInt: \"uint\",\n\n /** Unsigned 8-bit integer (between 0 and 255, 1 byte). */\n UInt8: \"u8\",\n\n /** Unsigned 16-bit integer (between 0 and 65,535, 2 bytes). */\n UInt16: \"u16\",\n\n /** Unsigned 32-bit integer (between 0 and 4,294,967,295, 4 bytes). */\n UInt32: \"u32\",\n\n /**\n * Signed integer (1 - 8 bytes).\n * - 0 → ±64 = 1 byte\n * - ±65 → ±8,192 = 2 bytes\n * - ±8,193 → ±268,435,456 = 4 bytes\n * - ±268,435,457 → ±`Number.MAX_SAFE_INTEGER` = 8 bytes\n */\n Int: \"int\",\n\n /** Signed 1 byte integer (between -127 and 127). */\n Int8: \"i8\",\n\n /** Signed 2 byte integer (between -32,767 and 32,767). */\n Int16: \"i16\",\n\n /** Signed 4 byte integer (between -2,147,483,647 and 2,147,483,647). */\n Int32: \"i32\",\n\n /** Default JavaScript `number` type. Floating-point number (64-bit, double precision, 8 bytes). */\n Float64: \"f64\",\n\n /** Floating-point number (32-bit, single precision, 4 bytes). */\n Float32: \"f32\",\n\n /**\n * Floating-point number (16-bit in FP16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision; maximum range: ±65,504.\n */\n Float16: \"f16\",\n\n /**\n * Floating-point number (16-bit in BF16 format, half precision, 2 bytes).\n *\n * **Warning:** Low precision.\n */\n BFloat16: \"b16\",\n\n /** A signed 2-decimal scalar between -1.00 and 1.00 (1 byte). */\n Scalar8: \"sc\",\n\n /** An unsigned 2-decimal scalar between 0.00 and 1.00 (1 byte). */\n UScalar8: \"usc\",\n\n /**\n * Boolean value (1 byte).\n * @see {Bools} for packing multiple booleans into a single byte.\n */\n Bool: \"bl\",\n\n /** Any array of booleans (1 bit overhead, encoded as UInt). */\n Bools: \"bls\",\n\n /** Any ArrayBuffer or ArrayBufferView (e.g. Uint8Array) value (encoded as 1 x UInt for byte length + buffer bytes). */\n Buffer: \"buf\",\n\n /** A UTF-8 string (encoded as 1 x UInt for UTF-8 byte length + UTF-8 bytes). */\n String: \"str\",\n\n /** Any JSON data (encodes as UTF-8). */\n JSON: \"jsn\",\n\n /** JavaScript RegExp object. */\n RegExp: \"re\",\n\n /**\n * JavaScript Date object.\n *\n * Encoded as an 8 byte (64-bit) integer UTC timestamp from as the number\n * of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).\n *\n * @see {Date}\n */\n Date: \"dt\",\n} as const;\n\nexport type TypeLiteral = typeof Type[keyof typeof Type];\nexport const ValidTypes = Object.values(Type);\n\n/**\n * Mappings for the value types.\n */\nexport type ValueTypes = {\n [Type.Int]: number;\n [Type.Int8]: number;\n [Type.Int16]: number;\n [Type.Int32]: number;\n [Type.UInt]: number;\n [Type.UInt8]: number;\n [Type.UInt16]: number;\n [Type.UInt32]: number;\n [Type.Float64]: number;\n [Type.Float32]: number;\n [Type.Float16]: number;\n [Type.BFloat16]: number;\n [Type.Scalar8]: number;\n [Type.UScalar8]: number;\n [Type.Bool]: boolean;\n [Type.Bools]: boolean[];\n [Type.Buffer]: Uint8Array | ArrayBuffer | ArrayBufferView;\n [Type.String]: string;\n [Type.JSON]: any;\n [Type.RegExp]: RegExp;\n [Type.Date]: Date;\n};\n\n/** https://www.totaltypescript.com/concepts/the-prettify-helper */\ntype Pretty = T extends ArrayBuffer | ArrayBufferView | Date | RegExp | Uint8Array ? T\n : T extends Array ? Array>\n : T extends object ? {[K in keyof T]: Pretty} & unknown : T;\n\n/** @throws any error too */\nexport type ValidationFn = (x: T) => undefined | boolean | Error;\nexport type TransformFn = (x: T) => T;\nexport type Transforms = TransformFn | [preEncode: TransformFn] | [preEncode: TransformFn | undefined, postDecode: TransformFn | undefined];\n\n/**\n * A wrapper around any Type definition that declares it as optional.\n */\nexport class MaybeType {\n public constructor(public type: T) {}\n}\n\n/**\n * Wrap any definition as optional.\n */\nexport function optional(t: T): MaybeType {\n return new MaybeType(t);\n}\n\n/**\n * A definition for an object binary encoder.\n */\nexport type EncoderDefinition = {\n [key: string]: FieldDefinition | MaybeType;\n};\n\n/**\n * Definition for an object-field binary encoder.\n */\nexport type FieldDefinition = keyof ValueTypes | [keyof ValueTypes] | EncoderDefinition | [EncoderDefinition] | MaybeType;\n\n/**\n * The resulting type of the decoded data, based on the encoder definition.\n */\ntype RawDecodedType = {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? never : EKey]: EncoderType[EKey] extends keyof ValueTypes\n ? ValueTypes[EncoderType[EKey]]\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Array\n : EncoderType[EKey] extends EncoderDefinition\n ? RawDecodedType\n : EncoderType[EKey] extends [EncoderDefinition]\n ? Array>\n : never;\n} & {\n [EKey in keyof EncoderType as EncoderType[EKey] extends MaybeType ? EKey : never]?: EncoderType[EKey] extends MaybeType\n ? ValueTypes[OptionalValue] | undefined\n : EncoderType[EKey] extends MaybeType\n ? Array | undefined\n : EncoderType[EKey] extends MaybeType\n ? RawDecodedType | undefined\n : never;\n};\n\nexport type DecodedType = Pretty>;\n\nexport type TransformConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? Transforms\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? Transforms\n : EncoderType[EKey] extends EncoderDefinition\n ? TransformConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? TransformConfig\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? Transforms\n : EncoderType[EKey] extends MaybeType\n ? TransformConfig | undefined\n : never;\n};\n\nexport type ValidationConfig = {\n [EKey in keyof EncoderType]?: EncoderType[EKey] extends keyof ValueTypes\n ? ValidationFn\n : EncoderType[EKey] extends [keyof ValueTypes]\n ? ValidationFn\n : EncoderType[EKey] extends EncoderDefinition\n ? ValidationConfig\n : EncoderType[EKey] extends [EncoderDefinition]\n ? ValidationConfig\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationFn\n : EncoderType[EKey] extends MaybeType\n ? ValidationConfig | undefined\n : never;\n};\n","/**\n * Mask booleans to a uint32.\n *\n * @param x - A boolean array.\n * @param padBit - A bit to pad the mask (for variable length data).\n */\nexport const mask = (x: boolean[], padBit: 0 | 1 = 0b1): number => {\n return x.reduce((n, b: any) => (n << 1) | b, padBit);\n};\n\n/**\n * Unmask booleans from a uint32.\n *\n * @param x - A uint32 number.\n * @param l - number of booleans to expect (default: infer lenth from x where x is encoded with a pad bit)\n * or pass an existing boolean array to decode in-place.\n */\nexport const unmask = (x: number, l?: number | boolean[]): boolean[] => {\n const len = l === undefined ? 31 - Math.clz32(x) : Array.isArray(l) ? l.length : l;\n const val = Array.isArray(l) && l.length === len ? l : new Array(len);\n for (let i = 0; i < len; i++) val[i] = !!(x & (1 << (len - 1 - i)));\n return val;\n};\n","export const $utf8encode = (function () {\n const encoder = new TextEncoder();\n return (x?: string): Uint8Array => encoder.encode(x);\n})();\n\nexport const $utf8decode = (function () {\n const decoder = new TextDecoder(\"utf-8\");\n return (y: Uint8Array): string => decoder.decode(y);\n})();\n","/**\n * Returns the nearest half precision float representation of a number.\n * @param x A numeric expression.\n */\nexport function f16round(x: number): number {\n return $fromf16($tof16(x));\n}\n\n/**\n * Returns the nearest half precision float representation of a number as a 16-bit bitmask.\n */\nexport const $tof16 = (function() {\n const x = new Float32Array(1);\n const y = new Int32Array(x.buffer);\n\n return function (f: number) {\n x[0] = f;\n let i = y[0]; // 32-bit int\n let s = (i >> 16) & 0X8000; // sign\n let z = (i & 0X7FFFFFFF) + 0X1000 | 0;\n\n if (z >= 0X47800000) {\n if ((i & 0X7FFFFFFF) < 0X47800000) return s | 0X7BFF;\n if (z < 0X7F800000) return s | 0X7C00;\n return s | 0X7C00 | (i & 0X007FFFFF) >> 13;\n }\n if (z >= 0X38800000) return s | z - 0X38000000 >> 13;\n else if (z < 0X33000000) return s;\n z = (i & 0X7FFFFFFF) >> 23;\n return s | ((i & 0X7FFFFF | 0X800000)\n + (0X800000 >>> z - 102)\n >> 126 - z);\n };\n}());\n\n/**\n * Returns the nearest half precision float value for a 16-bit bitmask.\n */\nexport const $fromf16 = (function() {\n const z = Math.pow(2, -24); // subnormal constant\n const d = new Float32Array(32 + 1024);\n for (let e = 0; e < 32; e++) d[e] = Math.pow(2, e - 15); // biased exponents\n for (let m = 0; m < 1024; m++) d[m + 0x20] = 1 + m / 1024; // normalized offset mantissas\n\n return function (b: number): number {\n const s = (b & 32768) === 32768 ? -1 : 1; // sign: 1 bit\n const e = b & 31744; // exponent: 5 bits\n const m = b & 1023; // mantissa: 10 bits\n\n if (e === 0) return m === 0 ? s * 0 : s * z;\n if (e === 31744) return m === 0 ? s * Infinity : NaN;\n return d[e >> 10] * d[m + 0x20] * s;\n };\n}());\n","const i = new Uint32Array(1);\nconst f = new Float32Array(i.buffer);\n\n/**\n * Returns the nearest bfloat16 representation of a number.\n * @param x A numeric expression.\n */\nexport function bf16round(x: number): number {\n f[0] = x;\n i[0] = i[0] & 0xFFFF0000;\n return f[0];\n}\n\n/** Returns a 16-bit bfloat16 bitmask for a given float. */\nexport function $tobf16(x: number): number {\n f[0] = x;\n return i[0] >>> 16;\n}\n\n/** Returns the nearest value from a 16-bit bfloat16 bitmask. */\nexport function $frombf16(x: number): number {\n i[0] = x << 16;\n return f[0];\n}\n","import { BufferWriter } from \"./BufferWriter\";\nimport { BufferReader } from \"./BufferReader\";\nimport {\n $fromuscal8,\n $fromscal8,\n $touscal8,\n $toscal8\n} from \"./scalar\";\nimport { TypeLiteral, Type } from \"../Type\";\nimport { mask, unmask } from \"./bitmask\";\nimport { $utf8decode, $utf8encode } from \"./utf8\";\nimport { $floor } from \"./math\";\nimport { $fromf16, $tof16 } from \"./float16\";\nimport { $frombf16, $tobf16 } from \"./bfloat16\";\n\n// Pre-calculated constants\nconst MAX_VARUINT8 = 128,\n MAX_VARUINT16 = 16_384,\n MAX_VARUINT32 = 536_870_912,\n MAX_VARINT8 = 64,\n MAX_VARINT16 = 8_192,\n MAX_VARINT32 = 268_435_456,\n POW_32 = 0x100000000;\n\ntype WriterFn = (value: W, writer: BufferWriter) => void;\ntype ReaderFn = (reader: BufferReader, overwrite?: Partial) => R;\n\nexport interface BinaryTypeCoder {\n $write: WriterFn;\n $read: ReaderFn;\n}\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const uintCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value < 0) value = 0;\n if (value < MAX_VARUINT8) writer.$writeUint8(value);\n else if (value < MAX_VARUINT16) writer.$writeUint16(value + 0x8000);\n else if (value < MAX_VARUINT32) writer.$writeUint32((value + 0xc0000000) | 0);\n else if (value >= MAX_VARUINT32) {\n writer.$writeUint32(($floor(value / POW_32) + 0xe0000000) | 0);\n writer.$writeUint16(value >>> 16);\n writer.$writeUint16(value & 0xffff);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 1 : 0);\n }\n },\n $read: (reader) => {\n const firstByte = reader.$peek();\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return firstByte;\n }\n else if (!(firstByte & 0x40)) {\n return reader.$readUint16() - 0x8000;\n }\n else if (!(firstByte & 0x20)) {\n return reader.$readUint32() - 0xc0000000;\n }\n\n return (reader.$readUint32() - 0xe0000000) * POW_32\n + reader.$readUint32();\n }\n};\n\nexport const uint8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value),\n $read: (reader) => reader.$readUint8(),\n};\n\nexport const uint16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16(value),\n $read: (reader) => reader.$readUint16(),\n};\n\nexport const uint32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint32(value),\n $read: (reader) => reader.$readUint32(),\n};\n\n/**\n * Format (big-endian):\n * 7b 0xxxxxxx\n * 14b 10xxxxxx xxxxxxxx\n * 29b 110xxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n * 61b 111xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx\n */\nexport const intCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (typeof value !== \"number\") value = Number(value);\n if (value >= -MAX_VARINT8 && value < MAX_VARINT8) writer.$writeUint8(value & 0x7f);\n else if (value >= -MAX_VARINT16 && value < MAX_VARINT16) writer.$writeUint16((value & 0x3fff) + 0x8000);\n else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) | 0xc0000000);\n else if (value < -MAX_VARINT32 || value >= MAX_VARINT32) {\n // Split in two 32b uints\n writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) | 0xe0000000);\n writer.$writeUint16(value >>> 16);\n writer.$writeUint16(value & 0xffff);\n }\n else {\n // coercion case\n writer.$writeUint8(value as any === true ? 0x7f : 0);\n }\n },\n $read: (reader) => {\n let firstByte = reader.$peek(), i: number;\n\n if (!(firstByte & 0x80)) {\n reader.$skip();\n return (firstByte & 0x40) ? (firstByte | 0xffffff80) : firstByte;\n }\n else if (!(firstByte & 0x40)) {\n i = reader.$readUint16() - 0x8000;\n return (i & 0x2000) ? (i | 0xffffc000) : i;\n }\n else if (!(firstByte & 0x20)) {\n i = reader.$readUint32() - 0xc0000000;\n return (i & 0x10000000) ? (i | 0xe0000000) : i;\n }\n else {\n i = reader.$readUint32() - 0xe0000000;\n i = (i & 0x10000000) ? (i | 0xe0000000) : i;\n return i * POW_32 + reader.$readUint32();\n }\n }\n};\n\nexport const int8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt8(value),\n $read: (reader) => reader.$readInt8(),\n};\n\nexport const int16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt16(value),\n $read: (reader) => reader.$readInt16(),\n};\n\nexport const int32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeInt32(value),\n $read: (reader) => reader.$readInt32(),\n};\n\nexport const bfloat16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tobf16(value)),\n $read: (reader) => $frombf16(reader.$readUint16()),\n};\n\nexport const float16Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint16($tof16(value)),\n $read: (reader) => $fromf16(reader.$readUint16()),\n};\n\nexport const float32Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat32(value),\n $read: (reader) => reader.$readFloat32(),\n};\n\nexport const float64Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeFloat64(value),\n $read: (reader) => reader.$readFloat64(),\n};\n\nexport const uscalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($touscal8(value)),\n $read: (reader) => $fromuscal8(reader.$readUint8()),\n};\n\nexport const scalar8Coder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8($toscal8(value)),\n $read: (reader) => $fromscal8(reader.$readUint8()),\n};\n\nexport const dateCoder: BinaryTypeCoder = {\n $write: (value, writer) => intCoder.$write(value.getTime(), writer),\n $read: (reader) => new Date(intCoder.$read(reader)),\n};\n\nexport const bufferCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n uintCoder.$write(value.byteLength, writer); // prefix length\n writer.$writeBytes(value);\n },\n $read: (reader) => reader.$readBytes(uintCoder.$read(reader)),\n};\n\nexport const stringCoder: BinaryTypeCoder = {\n $write: (value, writer) => bufferCoder.$write($utf8encode(value), writer),\n $read: (reader) => $utf8decode(bufferCoder.$read(reader)),\n};\n\nexport const boolCoder: BinaryTypeCoder = {\n $write: (value, writer) => writer.$writeUint8(value ? 1 : 0),\n $read: (reader) => reader.$readUint8() !== 0,\n};\n\nexport const boolsCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n if (value.length > 28) value = value.slice(0, 28); // drop additional\n uintCoder.$write(mask(value), writer);\n },\n $read: (reader, p) => unmask(uintCoder.$read(reader), p),\n};\n\nexport const jsonCoder: BinaryTypeCoder = {\n $write: (value, writer) => stringCoder.$write(JSON.stringify(value), writer),\n $read: (reader) => JSON.parse(stringCoder.$read(reader)),\n};\n\nexport const regexCoder: BinaryTypeCoder = {\n $write: (value, writer) => {\n writer.$writeUint8(mask([value.global, value.ignoreCase, value.multiline]));\n stringCoder.$write(value.source, writer);\n },\n $read: (reader) => {\n const [g, i, m] = unmask(reader.$readUint8());\n return new RegExp(stringCoder.$read(reader), (g ? \"g\" : \"\") + (i ? \"i\" : \"\") + (m ? \"m\" : \"\"));\n }\n};\n\nexport const writers: Record> = {\n [Type.UInt]: uintCoder.$write,\n [Type.UInt8]: uint8Coder.$write,\n [Type.UInt16]: uint16Coder.$write,\n [Type.UInt32]: uint32Coder.$write,\n [Type.Int]: intCoder.$write,\n [Type.Int8]: int8Coder.$write,\n [Type.Int16]: int16Coder.$write,\n [Type.Int32]: int32Coder.$write,\n [Type.Float64]: float64Coder.$write,\n [Type.Float32]: float32Coder.$write,\n [Type.Float16]: float16Coder.$write,\n [Type.BFloat16]: bfloat16Coder.$write,\n [Type.Scalar8]: scalar8Coder.$write,\n [Type.UScalar8]: uscalar8Coder.$write,\n [Type.Bool]: boolCoder.$write,\n [Type.Bools]: boolsCoder.$write,\n [Type.Buffer]: bufferCoder.$write,\n [Type.String]: stringCoder.$write,\n [Type.JSON]: jsonCoder.$write,\n [Type.RegExp]: regexCoder.$write,\n [Type.Date]: dateCoder.$write,\n};\n\nexport const readers: Record> = {\n [Type.UInt]: uintCoder.$read,\n [Type.UInt8]: uint8Coder.$read,\n [Type.UInt16]: uint16Coder.$read,\n [Type.UInt32]: uint32Coder.$read,\n [Type.Int]: intCoder.$read,\n [Type.Int8]: int8Coder.$read,\n [Type.Int16]: int16Coder.$read,\n [Type.Int32]: int32Coder.$read,\n [Type.Float64]: float64Coder.$read,\n [Type.Float32]: float32Coder.$read,\n [Type.Float16]: float16Coder.$read,\n [Type.BFloat16]: bfloat16Coder.$read,\n [Type.Scalar8]: scalar8Coder.$read,\n [Type.UScalar8]: uscalar8Coder.$read,\n [Type.Bool]: boolCoder.$read,\n [Type.Bools]: boolsCoder.$read,\n [Type.Buffer]: bufferCoder.$read,\n [Type.String]: stringCoder.$read,\n [Type.JSON]: jsonCoder.$read,\n [Type.RegExp]: regexCoder.$read,\n [Type.Date]: dateCoder.$read,\n};\n","/** Default maximum transmission unit in networking */\nconst MTU = 1500;\n\n/** Set Tinybuf global config */\nexport const setTinybufConfig = (c: Partial): void => {\n cfg = { ...cfg, ...c };\n};\n\nexport type TinybufConfig = {\n /**\n * (default: false)\n *\n * This sets the default value for `preserveBytes` on\n * `encode(data, preserveBytes?)`.\n *\n * By default, `encode()` returns its encoded bytes as a `Uint8Array`\n * view of the bytes in the shared encoding buffer.\n *\n * This is suitable for synchronous use (e.g. high-performance applications)\n * as it avoids slow and expensive memory allocation and fragmentation on\n * each call to `encode()`.\n *\n * However, susbsequent calls are destructive to the underlying bytes, so\n * for asynchronous uses (e.g. Promises, Workers, long-lived storage), set\n * `preserveBytes` to `true`.\n */\n safe: boolean,\n\n /**\n * (default: true)\n * By default, format encoders share a global encoding buffer for performance\n * and memory management reasons.\n *\n * When set to false, each format is allocated an individual encoding buffer.\n *\n * Enable to maximise performance and memory re-use, just be cautious of\n * possible race conditions.\n */\n useGlobalEncodingBuffer: boolean,\n\n /**\n * (default: 1500)\n * The maximum bytes that can be allocated to an encoding buffer.\n *\n * Default is 1500 bytes, the standard \"Maximum Transmission Unit\".\n */\n encodingBufferMaxSize: number,\n\n /**\n * (default: 256)\n * Initial bytes to allocate for an encoding buffer.\n */\n encodingBufferInitialSize: number,\n\n /**\n * (default: 256)\n * Additional bytes to allocated when dynamically increasing the size of an encoding buffer.\n */\n encodingBufferIncrement: number,\n};\n\n/** @internal */\nexport let cfg: TinybufConfig = {\n safe: false,\n useGlobalEncodingBuffer: true,\n encodingBufferMaxSize: MTU,\n encodingBufferInitialSize: 256,\n encodingBufferIncrement: 256,\n};\n","import { cfg } from \"../config\";\nimport { TinybufError } from \"./errors\";\n\n/**\n * Wraps a buffer with a write head pointer.\n *\n * @internal\n */\nexport class BufferWriter {\n public $byteLength: number = 0;\n private _$dataView: DataView;\n private _$bytes: Uint8Array;\n private _$base: number;\n private _$writeHead: number = 0;\n private _$resizable: boolean;\n\n public constructor($0: number | Uint8Array) {\n this._$resizable = typeof $0 === \"number\";\n let b = $0 instanceof Uint8Array ? $0 : new Uint8Array($0);\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$dataView = new DataView(b.buffer);\n }\n\n /** Retarget the writer to a fixed-size byte array, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array): this {\n if (this._$dataView.buffer !== b.buffer) {\n this._$dataView = new DataView(b.buffer);\n }\n\n this._$bytes = b;\n this._$base = b.byteOffset;\n this._$resizable = false;\n this._$writeHead = 0;\n this.$byteLength = 0;\n\n return this;\n }\n\n public $viewBytes(): Uint8Array {\n return this._$bytes.subarray(0, this.$byteLength);\n }\n\n public $copyBytes(): Uint8Array {\n const buf = new Uint8Array(this.$byteLength);\n buf.set(this.$viewBytes());\n return buf;\n }\n\n // ----- Writers: -----\n\n public $writeInt8(value: number): void {\n this._$pre(1).setInt8(this._$writeHead, value);\n }\n\n public $writeInt16(value: number): void {\n this._$pre(2).setInt16(this._$writeHead, value, true);\n }\n\n public $writeInt32(value: number): void {\n this._$pre(4).setInt32(this._$writeHead, value, true);\n }\n\n public $writeUint8(value: number): void {\n this._$pre(1).setUint8(this._$writeHead, value);\n }\n\n public $writeUint16(value: number): void {\n this._$pre(2).setUint16(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeUint32(value: number): void {\n this._$pre(4).setUint32(this._$writeHead, value, false); // big-endian for varint\n }\n\n public $writeFloat32(value: number): void {\n this._$pre(4).setFloat32(this._$writeHead, value, true);\n }\n\n public $writeFloat64(value: number): void {\n this._$pre(8).setFloat64(this._$writeHead, value, true);\n }\n\n public $writeBytes(b: Uint8Array | ArrayBuffer | ArrayBufferView): void {\n // allocate bytes first\n this._$pre(b.byteLength);\n\n this._$bytes.set(\n b instanceof Uint8Array\n ? b\n : ArrayBuffer.isView(b)\n ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n : new Uint8Array(b),\n this._$writeHead - this._$base\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Pre-allocate some bytes on the dataview, moving the write head into\n * position.\n *\n * @throws TinybufError\n */\n private _$pre(bytes: number): DataView {\n if (this.$byteLength + bytes > this._$bytes.byteLength) {\n this._$malloc(bytes);\n }\n\n this._$writeHead = this._$base + this.$byteLength;\n this.$byteLength += bytes;\n\n return this._$dataView;\n }\n\n /**\n * @throws TinybufError\n */\n private _$malloc(bytes: number): void {\n if (!this._$resizable) {\n throw new TinybufError(\"exceeded buffer length: \" + this._$bytes.byteLength);\n }\n\n const currentBytes = this._$bytes.byteLength;\n const minNewBytes = this.$byteLength + bytes - currentBytes;\n const availableBytes = cfg.encodingBufferMaxSize - currentBytes;\n\n if (minNewBytes > availableBytes) {\n throw new TinybufError(\"exceeded encodingBufferMaxSize: \" + cfg.encodingBufferMaxSize);\n }\n\n const increment = cfg.encodingBufferIncrement;\n const newBytes = Math.ceil(minNewBytes / increment) * increment;\n const newSize = currentBytes + Math.min(newBytes, availableBytes);\n const buf = new Uint8Array(newSize);\n\n // copy bytes\n buf.set(this._$bytes);\n\n // update refs\n this._$dataView = new DataView(buf.buffer);\n this._$bytes = buf;\n this._$base = 0;\n }\n}\n","/**\n * Wraps a buffer with a read head pointer.\n *\n * @internal\n */\nexport class BufferReader {\n public i: number;\n private _$dataView!: DataView;\n private _$base!: number;\n private _$byteLength!: number;\n\n public constructor(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number) {\n this.$reset(b, headerBytes);\n }\n\n /** Retarget the reader to a new buffer, reusing the existing DataView where possible. */\n public $reset(b: Uint8Array | ArrayBufferView | ArrayBuffer, headerBytes?: number): this {\n const isView = ArrayBuffer.isView(b);\n const buffer = isView ? b.buffer : b;\n const offset = isView ? b.byteOffset : 0;\n let dv = this._$dataView;\n\n if (\n dv === undefined\n || dv.buffer !== buffer\n || offset < dv.byteOffset\n || offset + b.byteLength > dv.byteOffset + dv.byteLength\n ) {\n dv = this._$dataView = b instanceof DataView ? b : new DataView(buffer);\n }\n\n this._$base = offset - dv.byteOffset;\n this._$byteLength = b.byteLength;\n this.i = headerBytes ?? 0; // internal offset (header)\n\n return this;\n }\n\n /** Read the next byte, without moving the read head pointer. */\n public $peek(): number {\n if (this.i >= this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n return this._$dataView.getUint8(this._$base + this.i);\n }\n\n /** Skip the next byte without reading it. */\n public $skip(): void {\n this.i++;\n }\n\n // ----- Readers: -----\n\n public $readUint8(): number {\n return this._$dataView.getUint8(this._$at(1));\n }\n\n public $readUint16(): number {\n return this._$dataView.getUint16(this._$at(2)); // big-endian\n }\n\n public $readUint32(): number {\n return this._$dataView.getUint32(this._$at(4)); // big-endian\n }\n\n public $readInt8(): number {\n return this._$dataView.getInt8(this._$at(1));\n }\n\n public $readInt16(): number {\n return this._$dataView.getInt16(this._$at(2), true); // little-endian\n }\n\n public $readInt32(): number {\n return this._$dataView.getInt32(this._$at(4), true); // little-endian\n }\n\n public $readFloat32(): number {\n return this._$dataView.getFloat32(this._$at(4), true); // little-endian\n }\n\n public $readFloat64(): number {\n return this._$dataView.getFloat64(this._$at(8), true); // little-endian\n }\n\n /** @throws RangeError if exceeds length */\n public $readBytes(bytes: number): Uint8Array {\n return new Uint8Array(\n this._$dataView.buffer,\n this._$dataView.byteOffset + this._$at(bytes),\n bytes\n );\n }\n\n // ----- Private methods: -----\n\n /**\n * Advance the read head, returning the DataView offset to read from.\n *\n * @throws RangeError if exceeds length\n */\n private _$at(bytes: number): number {\n const i = this.i;\n\n if (i + bytes > this._$byteLength) {\n throw new RangeError(\"exceeded bytes\");\n }\n\n this.i = i + bytes;\n\n return this._$base + i;\n }\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { writers, readers } from \"./lib/coders\";\nimport * as coders from \"./lib/coders\";\nimport { $hashCode, $strToHashCode } from \"./lib/hashCode\";\nimport { peekHeader, peekHeaderStr } from \"./lib/peek\";\nimport { BufferWriter } from \"./lib/BufferWriter\";\nimport { BufferReader } from \"./lib/BufferReader\";\nimport {\n DecodedType,\n EncoderDefinition,\n FieldDefinition,\n TransformConfig,\n ValidationConfig,\n MaybeType,\n Transforms,\n TypeLiteral,\n ValidationFn,\n ValidTypes,\n} from \"./Type\";\nimport { cfg } from \"./config\";\n\nexport type FormatHeader = string | number;\n\n/**\n * Utility to get the decoded type of a buffer format\n * @example type Format = Decoded\n */\nexport type Decoded = TBufferFormat extends BufferFormat\n ? DecodedType\n : never;\n\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(def: T): BufferFormat;\n/**\n * Defines a format for encoding/decoding binary buffers.\n *\n * Optionally customize the identifier, either as a 2-byte string, an unsigned integer (0 -> 65,535), or as `null` to disable entirely.\n *\n * @example\n * const MyFormat = defineFormat({ ... });\n * const MyFormat = defineFormat('ab', { ... });\n * const MyFormat = defineFormat(1234, { ... });\n * const MyFormat = defineFormat(null, { ... });\n */\nexport function defineFormat(h: HeaderType | null, def: T): BufferFormat;\nexport function defineFormat(a?: HeaderType | T, b?: T): BufferFormat {\n return a !== null && typeof a === \"object\"\n ? new BufferFormat(a as T)\n : new BufferFormat(b as T, a as HeaderType);\n}\n\nfunction isValidHeader(h: FormatHeader): boolean {\n if (typeof h === \"number\") return Number.isInteger(h) && h >= 0 && h <= 65_535;\n if (typeof h === \"string\") return new TextEncoder().encode(h).byteLength === 2;\n return false;\n}\n\n/**\n * BufferFormat is a utility class for encoding and decoding binary data based\n * on a provided encoding format.\n *\n * @see {header}\n * @see {encode(data)}\n * @see {decode(binary)}\n */\nexport class BufferFormat {\n /** @internal */\n private static _$globalWriter?: BufferWriter;\n\n /**\n * A unique identifier encoded as the first 2 bytes (or `undefined` if headerless).\n *\n * @see {peekHeader(...)}\n * @see {peekHeaderStr(...)}\n */\n public header!: HeaderType;\n\n /** @internal */\n private _$header!: number; // always uint16 vesion\n /** @internal */\n private _$type!: TypeLiteral;\n /** @internal */\n private _$fields!: Field[];\n /** @internal */\n private _$fieldsMap!: Map;\n\n /** @internal */\n private _$format?: string;\n /** @internal */\n private _$transforms?: Transforms | undefined;\n /** @internal */\n private _$validate?: ValidationFn | undefined;\n /** @internal */\n private _$hasValidationOrTransforms = false;\n /** @internal */\n private _$writer?: BufferWriter;\n /** @internal */\n private _$intoWriter?: BufferWriter;\n /** @internal */\n private _$reader?: BufferReader;\n\n public constructor(\n def: EncoderType,\n header?: HeaderType | null,\n ) {\n // set definition\n if (typeof def === \"string\" && ValidTypes.includes(def)) {\n this._$type = def;\n }\n else if (def instanceof MaybeType) {\n throw new TypeError(\"Format cannot be optional\");\n }\n else if (def instanceof Object) {\n this._$type = undefined; // object\n this._$fieldsMap = new Map();\n this._$fields = Object.keys(def).map((name) => {\n const f = new Field(name, def[name]);\n this._$fieldsMap.set(name, f); // also set map entry\n return f;\n });\n\n // set headers\n if (header === undefined) {\n this.header = $hashCode(this.f) as HeaderType; // automatic\n this._$header = this.header as number;\n }\n else if (header === null) {\n this.header = undefined; // headerless\n this._$header = undefined;\n }\n else if (isValidHeader(header)) {\n this.header = header; // manual\n this._$header = typeof header === \"number\" ? header : $strToHashCode(header);\n }\n else {\n throw new TypeError(\"Header must be 2-byte string, uint16, or null.\");\n }\n }\n else {\n throw new TypeError(\"Format must be object or Type\");\n }\n }\n\n // ----- Static methods: -----\n\n /**\n * Read the header of a buffer as a number.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeader = peekHeader;\n\n /**\n * Read the header of a buffer as a string.\n *\n * @see {header}\n * @throws {RangeError} if buffer size < 2\n */\n public static peekHeaderStr = peekHeaderStr;\n\n // ----- Accessors: -----\n\n /**\n * @example \"{uint8,str[]?}\"\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private get f(): string {\n if (this._$format === undefined) {\n this._$format = this._$fields !== undefined\n ? `{${this._$fields.map(v => v.f).join(\",\")}}`\n : `${this._$type}`;\n }\n\n return this._$format;\n }\n\n /** @internal */\n private static _$initWriter(): BufferWriter {\n if (cfg.useGlobalEncodingBuffer) {\n if (!BufferFormat._$globalWriter) {\n this._$globalWriter = new BufferWriter(cfg.encodingBufferMaxSize);\n }\n\n return this._$globalWriter;\n }\n\n return new BufferWriter(cfg.encodingBufferInitialSize);\n }\n\n /**\n * Encode an object into an existing byte array.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n */\n public encodeInto>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): Uint8Array {\n return bytes.subarray(0, this.encodeIntoLength(data, bytes));\n }\n\n /**\n * Encode an object into an existing byte array, without allocating a view.\n *\n * @returns the number of bytes written to the start of `bytes`\n * @throws if fails to encode value to schema, or `bytes` is too small\n */\n public encodeIntoLength>(\n data: TDecodedType,\n bytes: Uint8Array,\n ): number {\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n const writer = this._$intoWriter?.$reset(bytes) ?? new BufferWriter(bytes);\n this._$intoWriter = undefined;\n\n try {\n this._$write(data, writer);\n\n return writer.$byteLength;\n }\n finally {\n this._$intoWriter = writer;\n }\n }\n\n /**\n * Encode an object to bytes.\n *\n * **Warning:** Returns an unsafe view into the encoding buffer. Pass this reference to preserve\n * performance, and to minimize memory allocation and fragmentation.\n *\n * @param data - data to encode\n * @param preserveBytes - (default: `setTinybufConfig().safe`) When set to true, copies encoded\n * bytes to a new buffer. When set to false, returns an unsafe view of bytes but prevents\n * unnnecessary memory allocation and fragmentation.\n *\n * @returns a copy of encoded bytes\n * @throws if fails to encode value to schema\n */\n public encode>(\n data: TDecodedType,\n preserveBytes?: boolean,\n ): Uint8Array {\n if (!this._$writer) {\n // lazy init\n this._$writer = BufferFormat._$initWriter();\n }\n\n // reset\n this._$writer.$byteLength = 0;\n\n if (this._$hasValidationOrTransforms) {\n data = this._$preprocess(data);\n }\n\n this._$write(data, this._$writer);\n\n return (preserveBytes ?? cfg.safe)\n ? this._$writer.$copyBytes()\n : this._$writer.$viewBytes();\n }\n\n /**\n * Decode binary data into an existing object instance.\n * @throws if fails to decode bytes to schema.\n */\n public decodeInto>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial,\n ): TDecodedType {\n return this._$decode(bytes, obj);\n }\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer\n ): TDecodedType;\n /**\n * @deprecated use decodeInto() instead\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto: Partial,\n ): TDecodedType;\n /**\n * Decode binary data to an object.\n * @throws if fails to decode bytes to schema.\n */\n public decode>(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n decodeInto?: Partial | undefined,\n ): TDecodedType {\n return this._$decode(bytes, decodeInto);\n }\n\n /**\n * Set additional transform functions to apply before encoding and after decoding.\n */\n public setTransforms(transforms: TransformConfig | Transforms): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof transforms === \"function\" || (Array.isArray(transforms) && typeof transforms[0] === \"function\")) {\n this._$transforms = transforms;\n }\n else {\n for (const name of Object.keys(transforms)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set transforms for field '${name}'`);\n }\n\n // Set validation for object.\n field.$coder.setTransforms(transforms[name]);\n }\n }\n\n return this;\n }\n\n /**\n * Set additional validation rules which are applied on encode() and decode().\n *\n * - Validation functions should throw an error, return an error, or return boolean false.\n * - Anything else is treated as successfully passing validation.\n */\n public setValidation(validations: ValidationConfig | ValidationFn): this {\n this._$hasValidationOrTransforms = true;\n\n if (typeof validations === \"function\") {\n this._$validate = validations;\n }\n else {\n for (const name of Object.keys(validations)) {\n const field = this._$fieldsMap.get(name);\n if (!field) {\n throw new TypeError(`Failed to set validation function for field '${name}'`);\n }\n\n field.$coder.setValidation(validations[name]);\n }\n }\n\n return this;\n }\n\n // ----- Implementation: -----\n\n /** @internal */\n private _$decode(\n bytes: Uint8Array | ArrayBufferView | ArrayBuffer,\n obj: Partial | undefined,\n ): TDecodedType {\n const headerBytes = this.header === undefined ? 0 : 2;\n\n const reader = this._$reader?.$reset(bytes, headerBytes) ?? new BufferReader(bytes, headerBytes);\n this._$reader = undefined;\n\n try {\n return this._$read(reader, obj);\n }\n finally {\n this._$reader = reader;\n }\n }\n\n /**\n * @param value\n * @param bw\n * @throws if the value is invalid\n *\n * @internal\n */\n private _$write(value: any, bw: BufferWriter): void {\n // write header\n if (this._$header !== undefined) bw.$writeUint16(this._$header);\n\n // write scalar\n if (this._$type !== undefined) {\n const safeValue = (this._$validate || this._$transforms) ? this._$preprocess(value) : value;\n\n return writers[this._$type](safeValue, bw);\n }\n\n // check for object type\n if (typeof value !== \"object\" || !value) {\n throw new TypeError(\"expected object type\");\n }\n\n // write each field\n const fields = this._$fields;\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const subValue = value[field.$name];\n\n if (field.$isOptional) {\n if (subValue === undefined || subValue === null) {\n coders.boolCoder.$write(false, bw);\n continue; // skip\n }\n else {\n coders.boolCoder.$write(true, bw);\n }\n }\n else if (subValue == null) {\n throw new Error(`missing required value: ${field.$name}`);\n }\n\n if (field.$isArray) {\n // array\n this._$writeArray(subValue, bw, field.$coder);\n continue;\n }\n\n // scalar/object field\n field.$coder._$write(subValue, bw);\n }\n }\n\n /**\n * pre-process: validation and/or transforms\n * @internal\n */\n private _$preprocess>(data: T): T {\n if (this._$validate) this._$processValidation(data);\n\n if (typeof this._$transforms === \"function\") {\n return this._$transforms(data);\n }\n else if (Array.isArray(this._$transforms) && typeof this._$transforms[0] === \"function\") {\n return this._$transforms[0](data);\n }\n\n return data;\n }\n\n /**\n * post-process: validation and/or transforms\n * @internal\n */\n private _$postprocess>(data: T): T {\n if (Array.isArray(this._$transforms) && typeof this._$transforms[1] === \"function\") {\n data = this._$transforms[1](data);\n }\n\n if (this._$validate) this._$processValidation(data);\n\n return data;\n }\n\n private _$processValidation(data: any): void {\n if (!this._$validate) return;\n const res = this._$validate(data);\n if (res instanceof Error) throw res;\n if (res === false) throw new Error(\"failed validation\");\n }\n\n /**\n * This function will be executed only the first time\n * After that, we'll compile the read routine and add it directly to the instance\n * @param state\n * @returns\n * @throws if fails\n *\n * @internal\n */\n private _$read>(state: BufferReader, obj?: Partial): TDecodedType {\n // This function will be executed only the first time to compile the read routine.\n // After that, we'll compile the read routine and add it directly to the instance\n\n // Update the read method implementation.\n this._$read = this._$compileFormatReadFn();\n\n return this._$read(state, obj);\n }\n\n /**\n * Generate read function code for this coder.\n *\n * @example\n * let v=o??{};\n * v.prop1=this._$readField(0,s,o);\n * v.prop2=this._$readField(1,s,o);\n * return v\n *\n * @internal\n */\n private _$makeObjectReadFnBody(): string {\n const fieldsStr: string = this._$fields\n .map(({ $name: n }, i) => `v.${n}=this.${this._$readField.name}(${i},s,v.${n})`)\n .join(\";\");\n\n return `let v=o??{};${fieldsStr};return v;`;\n }\n\n /**\n * Read an individual field.\n * @internal\n */\n private _$readField(fieldIndex: number, state: BufferReader, obj?: any): any {\n const field = this._$fields[fieldIndex];\n\n if (field.$isOptional && !coders.boolCoder.$read(state)) {\n return undefined;\n }\n\n if (field.$isArray) {\n return this._$readArray(field.$coder, state, obj);\n }\n\n return field.$coder._$read(state, obj);\n }\n\n /**\n * Compile the decode() method for this object.\n *\n * @internal\n */\n private _$compileFormatReadFn>(): (state: BufferReader, obj: Partial | undefined) => TDecodedType {\n if (this._$type !== undefined) {\n // scalar type\n return this._$hasValidationOrTransforms\n ? (s) => this._$postprocess(readers[this._$type](s))\n : readers[this._$type];\n }\n\n // object type\n return new Function(\"s\", \"o\", this._$makeObjectReadFnBody()) as any;\n }\n\n /**\n * @internal\n */\n private _$writeArray(value: any[], bw: BufferWriter, type: BufferFormat): void {\n if (!Array.isArray(value)) {\n throw new TypeError(`expected array, instead got: ${value}`);\n }\n\n coders.uintCoder.$write(value.length, bw);\n for (let i = 0; i < value.length; i++) {\n type._$write(value[i], bw);\n }\n }\n\n /**\n * @throws if invalid data\n * @internal\n */\n private _$readArray(type: BufferFormat, state: any, obj?: Array): Array {\n const len = coders.uintCoder.$read(state);\n const arr = Array.isArray(obj) ? obj : new Array(len);\n if (arr.length !== len) arr.length = len;\n for (let j = 0; j < arr.length; j++) {\n arr[j] = type._$read(state, obj?.[j]);\n }\n return arr;\n }\n}\n\n/**\n * Parses and represents an object field.\n *\n * @internal\n */\nclass Field {\n public $name: string;\n public $coder: BufferFormat;\n public $isOptional: boolean;\n public $isArray: boolean;\n\n private _$formatString?: string;\n\n public constructor(name: string, rawType: FieldDefinition) {\n this.$isOptional = rawType instanceof MaybeType;\n let type = rawType instanceof MaybeType ? rawType.type : rawType;\n\n this.$name = name;\n\n if (Array.isArray(type)) {\n if (type.length !== 1) {\n throw new TypeError(\"Array type must contain exactly one format\");\n }\n\n type = type[0];\n this.$isArray = true;\n }\n else {\n this.$isArray = false;\n }\n\n this.$coder = new BufferFormat(type, null);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public get f(): string {\n if (this._$formatString === undefined) {\n this._$formatString = `${(this.$coder as any).f}${this.$isArray ? \"[]\" : \"\"}${this.$isOptional ? \"?\" : \"\"}`;\n }\n\n return this._$formatString;\n }\n}\n"],"names":["TinybufError","Error","$hashCode","str","hash","i","length","charCodeAt","$strToHashCode","$hashCodeToStr","hashCode","String","fromCharCode","Math","floor","peekHeader","b","byteLength","RangeError","Uint8Array","DataView","getUint16","u8","ArrayBuffer","isView","buffer","byteOffset","peekHeaderStr","bufferParser","BufferParser","constructor","this","_$formats","Map","_$data","processBuffer","f","data","cb","r","header","has","get","_a","decode","set","e","err","stack","on","format","callback","decodeInPlace","ignore","forEach","clear","$floor","$ceil","ceil","$clamp","value","min","max","$roundTowardZero","x","$roundAwayFromZero","uscalround","$fromuscal8","$touscal8","scalround","$fromscal8","$toscal8","Type","UInt","UInt8","UInt16","UInt32","Int","Int8","Int16","Int32","Float64","Float32","Float16","BFloat16","Scalar8","UScalar8","Bool","Bools","Buffer","JSON","RegExp","Date","ValidTypes","Object","values","MaybeType","type","optional","t","mask","padBit","reduce","n","unmask","l","len","undefined","clz32","Array","isArray","val","$utf8encode","encoder","TextEncoder","encode","$utf8decode","decoder","TextDecoder","y","f16round","$fromf16","$tof16","Float32Array","Int32Array","s","z","pow","d","m","Infinity","NaN","Uint32Array","bf16round","MAX_VARUINT32","MAX_VARINT32","POW_32","uintCoder","$write","writer","Number","$writeUint8","$writeUint16","$writeUint32","$read","reader","firstByte","$peek","$readUint32","$readUint16","$skip","uint8Coder","$readUint8","uint16Coder","uint32Coder","intCoder","int8Coder","$writeInt8","$readInt8","int16Coder","$writeInt16","$readInt16","int32Coder","$writeInt32","$readInt32","bfloat16Coder","$tobf16","$frombf16","float16Coder","float32Coder","$writeFloat32","$readFloat32","float64Coder","$writeFloat64","$readFloat64","uscalar8Coder","scalar8Coder","dateCoder","getTime","bufferCoder","$writeBytes","$readBytes","stringCoder","boolCoder","boolsCoder","slice","p","jsonCoder","stringify","parse","regexCoder","global","ignoreCase","multiline","source","g","writers","readers","setTinybufConfig","c","cfg","assign","safe","useGlobalEncodingBuffer","encodingBufferMaxSize","encodingBufferInitialSize","encodingBufferIncrement","BufferWriter","$0","$byteLength","_$writeHead","_$resizable","_$bytes","_$base","_$dataView","$reset","$viewBytes","subarray","$copyBytes","buf","_$pre","setInt8","setInt16","setInt32","setUint8","setUint16","setUint32","setFloat32","setFloat64","bytes","_$malloc","currentBytes","minNewBytes","availableBytes","increment","newBytes","newSize","BufferReader","headerBytes","offset","dv","_$byteLength","getUint8","_$at","getUint32","getInt8","getInt16","getInt32","getFloat32","getFloat64","defineFormat","a","BufferFormat","def","_$hasValidationOrTransforms","includes","_$type","TypeError","_$fieldsMap","_$fields","keys","map","name","Field","_$header","isValidHeader","h","isInteger","_$format","v","join","_$initWriter","_$globalWriter","encodeInto","encodeIntoLength","_$preprocess","_b","_$intoWriter","_$write","preserveBytes","_$writer","decodeInto","obj","_$decode","setTransforms","transforms","_$transforms","field","$coder","setValidation","validations","_$validate","_$reader","_$read","bw","safeValue","fields","subValue","$name","$isOptional","coders.boolCoder","$isArray","_$writeArray","_$processValidation","_$postprocess","res","state","_$compileFormatReadFn","_$makeObjectReadFnBody","fieldsStr","_$readField","fieldIndex","_$readArray","Function","coders.uintCoder","arr","j","rawType","_$formatString"],"mappings":"AAEM,MAAOA,qBAAqBC,OCM5B,SAAUC,UAAUC,GACxB,IAAIC,EAAO,KACX,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAC9BD,EAAe,GAAPA,EAAaD,EAAII,WAAWF,GAEtC,OAAc,MAAPD,CACT,CAQM,SAAUI,eAAeL,GAC7B,OAAmB,IAAfA,EAAIG,OAAqBJ,UAAUC,GACZ,IAApBA,EAAII,WAAW,GAAWJ,EAAII,WAAW,EAClD,CAKM,SAAUE,eAAeC,GAC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AAMH,GAC7CiN,EAAIrT,SAAWoG,IAAKiN,EAAIrT,OAASoG,GACrC,IAAK,IAAIkN,EAAI,EAAGA,EAAID,EAAIrT,OAAQsT,IAC9BD,EAAIC,GAAK3N,EAAKoM,GAAOa,EAAOxB,aAAA,EAAAA,EAAMkC,IAEpC,OAAOD,CACR,EA5Za/D,aAAU7O,WAAGA,WAQb6O,aAAajO,cAAGA,cA4ZhC,MAAM4O,MAQJ,WAAAzO,CAAmBwO,EAAcuD,GAC/B9R,KAAK4Q,GAAckB,aAAmB7N,UACtC,IAAIC,EAAO4N,aAAmB7N,UAAY6N,EAAQ5N,KAAO4N,EAIzD,GAFA9R,KAAK2Q,GAAQpC,EAETzJ,MAAMC,QAAQb,GAAO,CACvB,GAAoB,IAAhBA,EAAK3F,OACP,MAAM,IAAI2P,UAAU,8CAGtBhK,EAAOA,EAAK,GACZlE,KAAK8Q,IAAW,CACjB,MAEC9Q,KAAK8Q,IAAW,EAGlB9Q,KAAKiQ,GAAS,IAAIpC,aAAkB3J,EAAM,KAC3C,CAGD,KAAW7D,GAKT,YAJ4BuE,IAAxB5E,KAAK+R,KACP/R,KAAK+R,GAAiB,GAAI/R,KAAKiQ,GAAe5P,IAAIL,KAAK8Q,GAAW,KAAO,KAAK9Q,KAAK4Q,GAAc,IAAM,MAGlG5Q,KAAK+R,EACb"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 0743153..2065f7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "tinybuf", - "version": "1.9.0", + "version": "1.9.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "tinybuf", - "version": "1.9.0", + "version": "1.9.1", "license": "MIT", "devDependencies": { "@rollup/plugin-commonjs": "^26.0.1", diff --git a/package.json b/package.json index fb48a4f..0772c8b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tinybuf", - "version": "1.9.0", + "version": "1.9.1", "author": "Reece Como ", "authors": [ "Reece Como ", diff --git a/src/__tests__/coders.test.ts b/src/__tests__/coders.test.ts index 7150ee3..a748fce 100644 --- a/src/__tests__/coders.test.ts +++ b/src/__tests__/coders.test.ts @@ -259,6 +259,87 @@ describe("coders", () => { check(coder, -1 / Infinity); check(coder, NaN); }); + + it("writes little-endian IEEE 754 bytes for special values", () => { + [ + 0, -0, NaN, Infinity, -Infinity, + Number.MIN_VALUE, -Number.MIN_VALUE, 2.2250738585072009e-308, 2.2250738585072014e-308, + Number.MAX_VALUE, Number.EPSILON, Number.MAX_SAFE_INTEGER, Math.PI, + ].forEach(value => { + const expected = new Uint8Array(8); + new DataView(expected.buffer).setFloat64(0, value, true); + + expect(hexBytes(write(coder, value))).toEqual(hexBytes(expected)); + expect(Object.is(read(coder, write(coder, value)), value)).toBe(true); + }); + }); + }); + + describe("varint byte compatibility", () => { + const POW_32 = 0x100000000; + + function legacyUint(value: number): Uint8Array { + const dv = new DataView(new ArrayBuffer(8)); + if (value < 0) value = 0; + if (value < 128) dv.setUint8(0, value); + else if (value < 16_384) dv.setUint16(0, value + 0x8000); + else if (value < 536_870_912) dv.setUint32(0, value + 0xc0000000); + else if (value >= 536_870_912) { + dv.setUint32(0, Math.floor(value / POW_32) + 0xe0000000); + dv.setUint32(4, value >>> 0); + } + else return new Uint8Array([0]); + const len = value < 128 ? 1 : value < 16_384 ? 2 : value < 536_870_912 ? 4 : 8; + return new Uint8Array(dv.buffer, 0, len); + } + + function legacyInt(value: number): Uint8Array { + const dv = new DataView(new ArrayBuffer(8)); + let len: number; + if (value >= -64 && value < 64) { + dv.setUint8(0, value & 0x7f); len = 1; + } + else if (value >= -8_192 && value < 8_192) { + dv.setUint16(0, (value & 0x3fff) + 0x8000); len = 2; + } + else if (value >= -268_435_456 && value < 268_435_456) { + dv.setUint32(0, (value & 0x1fffffff) + 0xc0000000); len = 4; + } + else if (value < -268_435_456 || value >= 268_435_456) { + dv.setUint32(0, (Math.floor(value / POW_32) & 0x1fffffff) + 0xe0000000); + dv.setUint32(4, value >>> 0); + len = 8; + } + else return new Uint8Array([0]); + return new Uint8Array(dv.buffer, 0, len); + } + + const values: number[] = [ + Infinity, -Infinity, Number.MAX_VALUE, Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER, + 2 ** 61, 2 ** 62 + 12345, 2 ** 32, 2 ** 32 - 1, 2 ** 31, -(2 ** 31), 2 ** 30, -(2 ** 30), + Date.UTC(2026, 10, 9), -Date.UTC(2026, 10, 9), 16_384.5, 536_870_911.9, -268_435_456.5, + ]; + for (let e = 0; e <= 62; e++) { + const p = 2 ** e; + values.push(p - 1, p, p + 1, -p - 1, -p, -p + 1); + } + for (let i = 0; i < 2000; i++) { + values.push(Math.floor((Math.random() - 0.5) * 2 ** (Math.random() * 63))); + } + + it("uintCoder writes the same bytes as before", () => { + values.forEach(value => { + expect(`${value}: ${hexBytes(write(coders.uintCoder, value))}`) + .toEqual(`${value}: ${hexBytes(legacyUint(value))}`); + }); + }); + + it("intCoder writes the same bytes as before", () => { + values.forEach(value => { + expect(`${value}: ${hexBytes(write(coders.intCoder, value))}`) + .toEqual(`${value}: ${hexBytes(legacyInt(value))}`); + }); + }); }); describe("uscalar8Coder", () => { diff --git a/src/core/BufferFormat.ts b/src/core/BufferFormat.ts index a83937c..57e64d8 100644 --- a/src/core/BufferFormat.ts +++ b/src/core/BufferFormat.ts @@ -405,7 +405,9 @@ export class BufferFormat = { if (value < 0) value = 0; if (value < MAX_VARUINT8) writer.$writeUint8(value); else if (value < MAX_VARUINT16) writer.$writeUint16(value + 0x8000); - else if (value < MAX_VARUINT32) writer.$writeUint32(value + 0xc0000000); + else if (value < MAX_VARUINT32) writer.$writeUint32((value + 0xc0000000) | 0); else if (value >= MAX_VARUINT32) { - writer.$writeUint32($floor(value / POW_32) + 0xe0000000); - writer.$writeUint32(value >>> 0); + writer.$writeUint32(($floor(value / POW_32) + 0xe0000000) | 0); + writer.$writeUint16(value >>> 16); + writer.$writeUint16(value & 0xffff); } else { // coercion case @@ -99,11 +100,12 @@ export const intCoder: BinaryTypeCoder = { if (typeof value !== "number") value = Number(value); if (value >= -MAX_VARINT8 && value < MAX_VARINT8) writer.$writeUint8(value & 0x7f); else if (value >= -MAX_VARINT16 && value < MAX_VARINT16) writer.$writeUint16((value & 0x3fff) + 0x8000); - else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) + 0xc0000000); + else if (value >= -MAX_VARINT32 && value < MAX_VARINT32) writer.$writeUint32((value & 0x1fffffff) | 0xc0000000); else if (value < -MAX_VARINT32 || value >= MAX_VARINT32) { // Split in two 32b uints - writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) + 0xe0000000); - writer.$writeUint32(value >>> 0); + writer.$writeUint32(($floor(value / POW_32) & 0x1fffffff) | 0xe0000000); + writer.$writeUint16(value >>> 16); + writer.$writeUint16(value & 0xffff); } else { // coercion case