UNPKG

gnablib

Version:

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

2 lines 2.83 kB
/*! Copyright 2023-2024 the gnablib contributors MPL-1.1 */ import{ContentError as t}from"../error/ContentError.js";const e="=",r=31;class a{constructor(t,e){this.tbl=t,this._decode=this.buildDecode(e),this.reqPad=e.requirePad,e.makeTblLower&&(this.tbl=t.toLowerCase())}buildDecode(t){const r=new Uint8Array(127);r[e.charCodeAt(0)]=33;for(let t=0;t<32;){const e=t++;r[this.tbl.charCodeAt(e)]=t,r[32|this.tbl.charCodeAt(e)]=t}if(t.extraDecodes)for(const e in t.extraDecodes)r[e.charCodeAt(0)]=t.extraDecodes[e]+1;return r}fromBytes(t,a){null==a&&(a=this.reqPad);let h="",c=4;for(;c<t.length;c+=5)h+=this.tbl.charAt(t[c-4]>>>3)+this.tbl.charAt((t[c-4]<<2|t[c-3]>>>6)&r)+this.tbl.charAt(t[c-3]>>>1&r)+this.tbl.charAt((t[c-3]<<4|t[c-2]>>>4)&r)+this.tbl.charAt((t[c-2]<<1|t[c-1]>>>7)&r)+this.tbl.charAt(t[c-1]>>>2&r)+this.tbl.charAt((t[c-1]<<3|t[c]>>>5)&r)+this.tbl.charAt(t[c]&r);switch(t.length-c+5-1){case 1:h+=this.tbl.charAt(t[c-4]>>>3)+this.tbl.charAt(t[c-4]<<2&r),a&&(h+="======");break;case 2:h+=this.tbl.charAt(t[c-4]>>>3)+this.tbl.charAt((t[c-4]<<2|t[c-3]>>>6)&r)+this.tbl.charAt(t[c-3]>>>1&r)+this.tbl.charAt(t[c-3]<<4&r),a&&(h+="====");break;case 3:h+=this.tbl.charAt(t[c-4]>>>3)+this.tbl.charAt((t[c-4]<<2|t[c-3]>>>6)&r)+this.tbl.charAt(t[c-3]>>>1&r)+this.tbl.charAt((t[c-3]<<4|t[c-2]>>>4)&r)+this.tbl.charAt(t[c-2]<<1&r),a&&(h+="===");break;case 4:h+=this.tbl.charAt(t[c-4]>>>3)+this.tbl.charAt((t[c-4]<<2|t[c-3]>>>6)&r)+this.tbl.charAt(t[c-3]>>>1&r)+this.tbl.charAt((t[c-3]<<4|t[c-2]>>>4)&r)+this.tbl.charAt((t[c-2]<<1|t[c-1]>>>7)&r)+this.tbl.charAt(t[c-1]>>>2&r)+this.tbl.charAt(t[c-1]<<3&r),a&&(h+=e)}return h}toBytes(e,r){const a="toBytes",h=new Uint8Array(Math.ceil(5*e.length/8));let c=0,i=0,s=0,o=0,n=0;for(;n<e.length;n++){const r=this._decode[e.charCodeAt(n)];if(0===r)throw new t("Unknown char",a,e.charAt(n));if(33!==r){if(c>0)throw new t("Found after padding",a,e.charAt(n));s=s<<5|r-1,o+=5,o>=8&&(o-=8,h[i++]=s>>o)}else c++}switch(o){case 4:if(0===c&&!r)break;if(4!=c)throw new t("Bad padding, expecting 4 got",a,c);break;case 3:if(0===c&&!r)break;if(1!=c)throw new t("Bad padding, expecting 1 got",a,c);break;case 2:if(0===c&&!r)break;if(6!=c)throw new t("Bad padding, expecting 6 got",a,c);break;case 1:if(0===c&&!r)break;if(3!=c)throw new t("Bad padding, expecting 3 got",a,c);break;case 0:if(c>0)throw new t("Bad padding, expecting 0 got",a,c);break;default:throw new t("Incorrect character count",a,n)}return h.subarray(0,i)}}export const base32=new a("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",{requirePad:!0});export const zBase32=new a("YBNDRFG8EJKMCPQXOT1UWISZA345H769",{requirePad:!1,makeTblLower:!0});export const base32hex=new a("0123456789ABCDEFGHIJKLMNOPQRSTUV",{requirePad:!0});export const crockford32=new a("0123456789ABCDEFGHJKMNPQRSTVWXYZ",{requirePad:!1,extraDecodes:{o:0,O:0,i:1,I:1,l:1,L:1}});