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