gnablib
Version:
A lean, zero dependency library to provide a useful base for your project.
2 lines • 1.3 kB
JavaScript
/*! Copyright 2023-2025 the gnablib contributors MPL-1.1 */
import{ParseProblem as e}from"../../error/index.js";export function parseDec(e){return/^\s*\d+\s*$/.test(e)?Number.parseInt(e,10):Number.NaN}export function parseHex(e){return/^\s*(?:0x)?([a-fA-F0-9]+)\s*$/.test(e)?parseInt(e,16):Number.NaN}export function sign8(e){return(e&=255)>127&&(e=~(255-e)),e}export function sign16(e){return(e&=65535)>32767&&(e=~(65535-e)),e}export function sign32(e){return 0|e}export function glScaleSize(e){return e<128?1:e<1024?2:Math.ceil(Math.log2(e+1)/8)+1}export function toGlScaleBytes(e){const t=new Uint8Array(5);if(e<128)return t[0]=e,t.subarray(0,1);if(e<1024)return t[0]=128|e>>>8,t[1]=e,t.subarray(0,2);let n=1;for(;0!=e;)t[n++]=e,e>>>=8;return t[0]=192|n-3,t.subarray(0,n)}export function fromGlScaleBytes(t){if(0==t.length)return new e("bytes","not enough content (need at least 1 byte)");const n=t[0];if(!(128&n))return[n,1];if(128==(192&n))return t.length<2?new e("bytes",`not enough content (need 2 bytes, got ${t.length})`):[(3&n)<<8|t[1],2];const r=2+(63&n);if(r>4)return new e("gscale",`too much content (need 4 bytes, told ${t.length})`);if(t.length<=r)return new e("bytes",`not enough content (need ${r} bytes, got ${t.length})`);let o=0;for(let e=0;e<r;e++)o|=t[e+1]<<8*e;return[o>>>0,r+1]}