foxts
Version:
Opinionated collection of common TypeScript utils by @SukkaW
1 lines • 1.63 kB
JavaScript
import{never as e}from"../guard/index.mjs";const t=Uint8Array,r=ArrayBuffer,n=TextDecoder,o=new TextEncoder,c=/=+$/,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=new Uint8Array(256);for(let e=0;e<l.length;e++)a[l.charCodeAt(e)]=e;function f(e){return o.encode(e)}const u={utf8:new n("utf8")};function i(e,t="utf8"){return u[t]??=new n(t),u[t].decode(e)}function A(e){const t=function(e){const t=e.replaceAll("-","+").replaceAll("_","/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}(e),r=t.length;let n=.75*t.length,o,c=0,l,f,u,i;"="===t[t.length-1]&&(n--,"="===t[t.length-2]&&n--);const A=new Uint8Array(new ArrayBuffer(n));for(o=0;o<r;o+=4)l=a[t.charCodeAt(o)],f=a[t.charCodeAt(o+1)],u=a[t.charCodeAt(o+2)],i=a[t.charCodeAt(o+3)],A[c++]=l<<2|f>>4,A[c++]=(15&f)<<4|u>>2,A[c++]=(3&u)<<6|63&i;return A}function h(e,t=!1){let r="";const n=e.length;for(let t=0;t<n;t+=3)r+=l[e[t]>>2],r+=l[(3&e[t])<<4|e[t+1]>>4],r+=l[(15&e[t+1])<<2|e[t+2]>>6],r+=l[63&e[t+2]];return n%3==2?r=r.slice(0,Math.max(0,r.length-1))+"=":n%3==1&&(r=r.slice(0,Math.max(0,r.length-2))+"=="),t?r.replaceAll("+","-").replaceAll("/","_").replace(c,""):r}function s(e,r){if(0===e.length)return new t(0);const n=new t(r??=e.reduce((e,t)=>e+t.length,0));let o=0;for(let t=0,r=e.length;t<r;t++){const r=e[t];n.set(r,o),o+=r.length}return n}function g(n){return n instanceof r?new t(n):r.isView(n)?new t(n.buffer,n.byteOffset,n.byteLength):void e(n,"value must be ArrayBuffer or ArrayBufferView")}export{A as base64ToUint8Array,s as concatUint8Arrays,f as stringToUint8Array,g as toUint8Array,h as uint8ArrayToBase64,i as uint8ArrayToString};