gnablib
Version:
A lean, zero dependency library to provide a useful base for your project.
2 lines • 1.81 kB
JavaScript
/*! Copyright 2024 the gnablib contributors MPL-1.1 */
import{ContentError as t}from"../../error/ContentError.js";import{sLen as r,sNum as e}from"../../safe/safe.js";const i=Symbol.for("nodejs.util.inspect.custom"),s="Micro",n=1e6;export class Micro{constructor(t){this._v=t}toString(){return this.valueOf().toString()}toPadString(){const t=this.valueOf().toString();return("000000"+t).substring(t.length)}toJSON(){return this._v[0]<<16|this._v[1]<<8|this._v[2]}valueOf(){return this._v[0]<<16|this._v[1]<<8|this._v[2]}serialize(t){t.mustPushNumberBE(this.valueOf(),Micro.serialBits)}get serialSizeBits(){return o.serialBits}validate(){return e("value",this.valueOf()).lt(n).throwNot(),this}get[Symbol.toStringTag](){return s}[i](){return`${s}(${this.toString()})`}fill(t){t[0]=this._v[0],t[1]=this._v[1],t[2]=this._v[2]}cloneTo(t){return this.fill(t),new Micro(t)}static writeValue(t,r){t[0]=r>>16,t[1]=r>>8,t[2]=r}static setupStor(t){return t?(r("storage",t).atLeast(o.storageBytes).throwNot(),t):new Uint8Array(o.storageBytes)}static new(t,r){e("micro",t).unsigned().lt(n).throwNot();const i=o.setupStor(r);return o.writeValue(i,t),new Micro(i)}static parseIntoStorage(r,i,s,a,u="input"){r.trimStart();const l=r.match(/^(\d+)\s*$/);if(null==l)throw new t("expecting unsigned integer-string",u,r);const[,c]=l;let g=c;if(s&&6!=c.length)throw new t("expecting 6 digit unsigned integer-string",u,r);c.length<6&&a&&(g=(c+"000000").substring(0,6));const h=parseInt(g,10);e(u,h).unsigned().lt(n).throwNot(),o.writeValue(i,h),r.shrink(c.length)}static parse(t,r=!1,e=!1,i){const s=o.setupStor(i);return o.parseIntoStorage(t,s,r,e,"micro"),new Micro(s)}static deserialize(t,r){const e=o.setupStor(r);return o.writeValue(e,t.readNumberBE(o.serialBits)),new Micro(e)}}Micro.storageBytes=3,Micro.serialBits=20;const o=Micro;