UNPKG

gnablib

Version:

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

2 lines 2.78 kB
/*! Copyright 2023-2024 the gnablib contributors MPL-1.1 */ import{sNum as t}from"../safe/safe.js";const o=Math.pow(2,-11)-Math.pow(2,-77),e=255,n=127,s=Math.pow(2,-24)-Math.pow(2,-77),a=2047,f=1023;function r(t){return 1-(t>>6&2)}export const fpb16={EPSILON:.0009765625,MAX_INT:2048,toBytes:function(t){const e=new Uint8Array(2),n=t<0||0===t&&1/t<0?1:0;let s=0,a=0;if(t*=1-2*n,Number.isNaN(t))s=2047,a=31;else if(t===1/0)a=31;else{let e;a=Math.floor(Math.log2(t)),t*(e=Math.pow(2,-a))<1&&(a--,e*=2),(t+=a+15>0?o/e:o*Math.pow(2,-14))*e>=2&&(a++,e/=2);const n=a+15;n>=31?(s=0,a=31):n>0?(s=(t*e-1)*Math.pow(2,10),a=n):(s=t*Math.pow(2,14)*Math.pow(2,10),a=0)}return e[0]=n<<7|a<<2|s>>8,e[1]=s,e},fromBytesUnsafe:function(t,o){const e=r(t[o]);let n=t[o]>>2&31,s=(3&t[o])<<8|t[o+1];switch(n){case 31:return s?NaN:e*(1/0);case 0:n+=1;break;default:s|=1024}return e*s*Math.pow(2,n-15-10)},fromBytes:function(o,e=0){return t("pos",e).unsigned().atMost(o.length-2).throwNot(),fpb16.fromBytesUnsafe(o,e)}};export const fpb32={EPSILON:1.1920928955078125e-7,MAX_INT:16777216,toBytes:function(t){const o=new Uint8Array(4),a=t<0||0===t&&1/t<0?1:0;let f=0,r=0;if(t*=1-2*a,Number.isNaN(t))f=8388607,r=e;else if(t===1/0)r=e;else{let o;r=Math.floor(Math.log2(t)),t*(o=Math.pow(2,-r))<1&&(r--,o*=2),(t+=r+n>0?s/o:s*Math.pow(2,-126))*o>=2&&(r++,o/=2);const a=r+n;a>=e?(f=0,r=e):a>0?(f=(t*o-1)*Math.pow(2,23),r=a):(f=t*Math.pow(2,126)*Math.pow(2,23),r=0)}return o[0]=a<<7|r>>1,o[1]=r<<7|f>>16,o[2]=f>>8,o[3]=f,o},fromBytesUnsafe:function(t,o){const s=r(t[o]);let a=(127&t[o])<<1|t[o+1]>>7,f=(127&t[o+1])<<16|t[o+2]<<8|t[o+3];switch(a){case e:return f?NaN:s*(1/0);case 0:a+=1;break;default:f|=8388608}return s*f*Math.pow(2,a-n-23)},fromBytes:function(o,e=0){return t("pos",e).unsigned().atMost(o.length-4).throwNot(),fpb32.fromBytesUnsafe(o,e)}};export const fpb64={EPSILON:Number.EPSILON,MAX_INT:9007199254740992,toBytes:function(t){const o=new Uint8Array(8),e=t<0||0===t&&1/t<0?1:0;let n=0,s=0;if(t*=1-2*e,Number.isNaN(t))n=0xfffffffffffff,s=a;else if(t===1/0)s=a;else{let o;s=Math.floor(Math.log2(t)),t*(o=Math.pow(2,-s))<1&&(s--,o*=2),t*o>=2&&(s++,o/=2);const e=s+f;e>=a?(n=0,s=a):e>0?(n=(t*o-1)*Math.pow(2,52),s=e):(n=t*Math.pow(2,1022)*Math.pow(2,52),s=0)}const r=n/16777216|0;return o[0]=e<<7|s>>4,o[1]=s<<4|r>>24,o[2]=r>>16,o[3]=r>>8,o[4]=r,o[5]=n>>16,o[6]=n>>8,o[7]=n,o},fromBytesUnsafe:function(t,o){const e=r(t[o]);let n=(127&t[o])<<4|t[o+1]>>4,s=(15&t[o+1])<<24|t[o+2]<<16|t[o+3]<<8|t[o+4];const h=t[o+5]<<16|t[o+6]<<8|t[o+7];switch(n){case a:return s||h?NaN:e*(1/0);case 0:n+=1;break;default:s|=268435456}const c=Math.pow(2,n-f-52+24);return e*(s*c+h*c*Math.pow(2,-24))},fromBytes:function(o,e=0){return t("pos",e).unsigned().atMost(o.length-8).throwNot(),fpb64.fromBytesUnsafe(o,e)}};