base64.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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.btoa || (
  12. object.btoa = 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("'btoa' 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.atob || (
  35. object.atob = function (input) {
  36. var str = String(input).replace(/=+$/, '');
  37. if (str.length % 4 == 1) {
  38. throw new InvalidCharacterError("'atob' 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. }());