UNPKG

@allex/base64

Version:

Lightweight performance optimized base64 library by Allex

10 lines 2.26 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 e,r;e=this,r=function(e){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split(""),n=String.fromCharCode,t=null,o=function(e){var r,n=-1,t=e.length,o=[];if(/^[\x00-\x7f]*$/.test(e))for(;++n<t;)o.push(e.charCodeAt(n));else for(;++n<t;)(r=e.charCodeAt(n))<128?o.push(r):r<2048?o.push(r>>6|192,63&r|128):o.push(r>>12|224,r>>6&63|128,63&r|128);return o},a=function(e){var n,o=[],a=new Array(4),i=-1;if(!t){for(n=r.length,t={};++i<n;)t[r[i]]=i;i=-1}for(n=e.length;++i<n&&(a[0]=t[e.charAt(i)],a[1]=t[e.charAt(++i)],o.push(a[0]<<2|a[1]>>4),a[2]=t[e.charAt(++i)],64!==a[2])&&(o.push((15&a[1])<<4|a[2]>>2),a[3]=t[e.charAt(++i)],64!==a[3]);)o.push((3&a[2])<<6|a[3]);return o},i=function(e){for(var n,t,a,i=o(e),c=i.length,f=new Array(4),d="",u=-1;++u<c;)n=i[u],t=i[++u],f[0]=n>>2,f[1]=(3&n)<<4|t>>4,isNaN(t)?f[2]=f[3]=64:(a=i[++u],f[2]=(15&t)<<2|a>>6,f[3]=isNaN(a)?64:63&a),d+=r[f[0]]+r[f[1]]+r[f[2]]+r[f[3]];return d},c=function(e,r){return r?i(String(e)).replace(/[+\/]/g,function(e){return"+"===e?"-":"_"}).replace(/=/g,""):i(String(e))};e.encode=c,e.decode=function(e){var r=(e=String(e)).length%4;return r&&(e+=Array(5-r).join("=")),function(e){if((e=e.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(e))throw new Error("InvalidCharacterError: decode failed: The string contains characters invalid in a base64 encoded string.");for(var r=a(e),t=r.length,o=0,i="";o<t;)r[o]<128?i+=n(r[o++]):r[o]>191&&r[o]<224?i+=n((31&r[o++])<<6|63&r[o++]):i+=n((15&r[o++])<<12|(63&r[o++])<<6|63&r[o++]);return i}(e.replace(/[-_]/g,function(e){return"-"===e?"+":"/"}).replace(/[^A-Za-z0-9=\+\/]/g,""))},e.encodeURI=function(e){return c(e,!0)},e.toUtf8=o,e.fromUtf8=a,Object.defineProperty(e,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e=e||self).Base64={}); /* 51097848ff46a559aabce23b9d31cfb7 */