UNPKG

gnablib

Version:

A lean, zero dependency library to provide a useful base for your project.

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