UNPKG

@allex/base64

Version:

Lightweight performance optimized base64 library by Allex

11 lines (10 loc) 2.05 kB
/*! * Lightweight performance optimized base64 library by Allex * * Copyright 2019, Allex Wang (https://iallex.com) * * Licensed under the MIT license: * https://opensource.org/licenses/MIT */ var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split(""),e=String.fromCharCode,n=null,t=function(r){var e,n=-1,t=r.length,a=[];if(/^[\x00-\x7f]*$/.test(r))for(;++n<t;)a.push(r.charCodeAt(n));else for(;++n<t;)(e=r.charCodeAt(n))<128?a.push(e):e<2048?a.push(e>>6|192,63&e|128):a.push(e>>12|224,e>>6&63|128,63&e|128);return a},a=function(e){var t,a=[],o=new Array(4),i=-1;if(!n){for(t=r.length,n={};++i<t;)n[r[i]]=i;i=-1}for(t=e.length;++i<t&&(o[0]=n[e.charAt(i)],o[1]=n[e.charAt(++i)],a.push(o[0]<<2|o[1]>>4),o[2]=n[e.charAt(++i)],64!==o[2])&&(a.push((15&o[1])<<4|o[2]>>2),o[3]=n[e.charAt(++i)],64!==o[3]);)a.push((3&o[2])<<6|o[3]);return a},o=function(e){for(var n,a,o,i=t(e),c=i.length,h=new Array(4),u="",f=-1;++f<c;)n=i[f],a=i[++f],h[0]=n>>2,h[1]=(3&n)<<4|a>>4,isNaN(a)?h[2]=h[3]=64:(o=i[++f],h[2]=(15&a)<<2|o>>6,h[3]=isNaN(o)?64:63&o),u+=r[h[0]]+r[h[1]]+r[h[2]]+r[h[3]];return u},i=function(r,e){return e?o(String(r)).replace(/[+\/]/g,(function(r){return"+"===r?"-":"_"})).replace(/=/g,""):o(String(r))},c=function(r){return i(r,!0)},h=function(r){var n=(r=String(r)).length%4;return n&&(r+=Array(5-n).join("=")),function(r){if((r=r.replace(/\s/g,"")).length%4)throw new Error("InvalidLengthError: decode failed: The string to be decoded is not the correct length for a base64 encoded string.");if(/[^A-Za-z0-9+/=\s]/g.test(r))throw new Error("InvalidCharacterError: decode failed: The string contains characters invalid in a base64 encoded string.");for(var n=a(r),t=n.length,o=0,i="";o<t;)n[o]<128?i+=e(n[o++]):n[o]>191&&n[o]<224?i+=e((31&n[o++])<<6|63&n[o++]):i+=e((15&n[o++])<<12|(63&n[o++])<<6|63&n[o++]);return i}(r.replace(/[-_]/g,(function(r){return"-"===r?"+":"/"})).replace(/[^A-Za-z0-9=\+\/]/g,""))};export{h as decode,i as encode,c as encodeURI,a as fromUtf8,t as toUtf8}; /* f413ae216e073bb327c47f35bf6c6754 */