base64.js 2.4 KB

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