You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.6 KiB

2 years ago
  1. ; (function () {
  2. var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
  3. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  4. function InvalidCharacterError(message) {
  5. this.message = message;
  6. }
  7. InvalidCharacterError.prototype = new Error;
  8. InvalidCharacterError.prototype.name = 'InvalidCharacterError';
  9. // encoder
  10. // [https://gist.github.com/999166] by [https://github.com/nignag]
  11. object.btoa2 || (
  12. object.btoa2 = function (input) {
  13. var str = String(input);
  14. for (
  15. // initialize result and counter
  16. var block, charCode, idx = 0, map = chars, output = '';
  17. // if the next str index does not exist:
  18. // change the mapping table to "="
  19. // check if d has no fractional digits
  20. str.charAt(idx | 0) || (map = '=', idx % 1);
  21. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  22. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  23. ) {
  24. charCode = str.charCodeAt(idx += 3 / 4);
  25. if (charCode > 0xFF) {
  26. throw new InvalidCharacterError("'btoa2' failed: The string to be encoded contains characters outside of the Latin1 range.");
  27. }
  28. block = block << 8 | charCode;
  29. }
  30. return output;
  31. });
  32. // decoder
  33. // [https://gist.github.com/1020396] by [https://github.com/atk]
  34. object.atob2 || (
  35. object.atob2 = function (input) {
  36. var str = String(input).replace(/=+$/, '');
  37. if (str.length % 4 == 1) {
  38. throw new InvalidCharacterError("'atob2' failed: The string to be decoded is not correctly encoded.");
  39. }
  40. for (
  41. // initialize result and counters
  42. var bc = 0, bs, buffer, idx = 0, output = '';
  43. // get next character
  44. buffer = str.charAt(idx++);
  45. // character found in table? initialize bit storage and add its ascii value;
  46. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  47. // and if not first of each 4 characters,
  48. // convert the first 8 bits to one ascii character
  49. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  50. ) {
  51. // try to find character in table (0-63, not found => -1)
  52. buffer = chars.indexOf(buffer);
  53. }
  54. return output;
  55. });
  56. }());