gnablib
Version:
A lean, zero dependency library to provide a useful base for your project.
2 lines • 1.94 kB
JavaScript
/*! Copyright 2023-2024 the gnablib contributors MPL-1.1 */
import{ContentError as n}from"../error/ContentError.js";const t="0123456789ABCDEF";function r(t){let r=t.charCodeAt(0);if(r<48)throw new n("unknown char","hex",t);if(r<=57)return r-48;if(r&=95,r<65||r>70)throw new n("unknown char","hex",t);return r-65+10}export const hex={fromByte:function(n){return t[n>>4&15]+t[15&n]},toByte:function(t){if(2!==t.length)throw new n("need pairs of (zero padded)","hex",t);return r(t[0])<<4|r(t[1])},fromI32Compress:function(n){let r=t[n>>4&15]+t[15&n];return n<256?r:(r=t[n>>12&15]+t[n>>8&15]+r,n<65536?r:(r=t[n>>20&15]+t[n>>16&15]+r,n<16777216?r:t[n>>>28&15]+t[n>>24&15]+r))},fromI32:function(n){return t[n>>>28&15]+t[n>>24&15]+t[n>>20&15]+t[n>>16&15]+t[n>>12&15]+t[n>>8&15]+t[n>>4&15]+t[15&n]},fromBytes:function(n){let r="";for(const o of n)r+=t[o>>4]+t[15&o];return r},fromU16s:function(n,r=""){let o="";for(const e of n)o+=t[e>>12&15]+t[e>>8&15]+t[e>>4&15]+t[15&e]+r;return o},fromU32s:function(n,r=""){let o="";for(const e of n)o+=t[e>>28&15]+t[e>>24&15]+t[e>>20&15]+t[e>>16&15]+t[e>>12&15]+t[e>>8&15]+t[e>>4&15]+t[15&e]+r;return o},fromU64:function(n){const r=n.toBytesBE();return t[r[0]>>4]+t[15&r[0]]+t[r[1]>>4]+t[15&r[1]]+t[r[2]>>4]+t[15&r[2]]+t[r[3]>>4]+t[15&r[3]]+t[r[4]>>4]+t[15&r[4]]+t[r[5]>>4]+t[15&r[5]]+t[r[6]>>4]+t[15&r[6]]+t[r[7]>>4]+t[15&r[7]]},fromU64a:function(n,r=""){let o="";for(let e=0;e<n.length;e++){const f=n.at(e).toBytesBE();o+=t[f[0]>>4]+t[15&f[0]]+t[f[1]>>4]+t[15&f[1]]+t[f[2]>>4]+t[15&f[2]]+t[f[3]>>4]+t[15&f[3]]+t[f[4]>>4]+t[15&f[4]]+t[f[5]>>4]+t[15&f[5]]+t[f[6]>>4]+t[15&f[6]]+t[f[7]>>4]+t[15&f[7]]+r}return o},toBytes:function(t,o){o=null!=o?o:"\t\n\f\r ";const e=new Uint8Array(Math.ceil(t.length/2));let f=0,u=0,c=0;for(const n of t){if(o.indexOf(n)>=0)continue;f=f<<4|r(n),u+=4,u>=8&&(u-=8,e[c++]=f>>>u&255)}if(4===u)throw new n("need pairs (zero padded) found extra","hex",15&f);return e.slice(0,c)}};