base64-arraybuffer.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * base64-arraybuffer
  3. * https://github.com/niklasvh/base64-arraybuffer
  4. *
  5. * Copyright (c) 2012 Niklas von Hertzen
  6. * Licensed under the MIT license.
  7. */
  8. (function(){
  9. "use strict";
  10. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  11. // Use a lookup table to find the index.
  12. var lookup = new Uint8Array(256);
  13. for (var i = 0; i < chars.length; i++) {
  14. lookup[chars.charCodeAt(i)] = i;
  15. }
  16. exports.encode = function(arraybuffer) {
  17. var bytes = new Uint8Array(arraybuffer),
  18. i, len = bytes.length, base64 = "";
  19. for (i = 0; i < len; i+=3) {
  20. base64 += chars[bytes[i] >> 2];
  21. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  22. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  23. base64 += chars[bytes[i + 2] & 63];
  24. }
  25. if ((len % 3) === 2) {
  26. base64 = base64.substring(0, base64.length - 1) + "=";
  27. } else if (len % 3 === 1) {
  28. base64 = base64.substring(0, base64.length - 2) + "==";
  29. }
  30. return base64;
  31. };
  32. exports.decode = function(base64) {
  33. var bufferLength = base64.length * 0.75,
  34. len = base64.length, i, p = 0,
  35. encoded1, encoded2, encoded3, encoded4;
  36. if (base64[base64.length - 1] === "=") {
  37. bufferLength--;
  38. if (base64[base64.length - 2] === "=") {
  39. bufferLength--;
  40. }
  41. }
  42. var arraybuffer = new ArrayBuffer(bufferLength),
  43. bytes = new Uint8Array(arraybuffer);
  44. for (i = 0; i < len; i+=4) {
  45. encoded1 = lookup[base64.charCodeAt(i)];
  46. encoded2 = lookup[base64.charCodeAt(i+1)];
  47. encoded3 = lookup[base64.charCodeAt(i+2)];
  48. encoded4 = lookup[base64.charCodeAt(i+3)];
  49. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  50. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  51. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  52. }
  53. return arraybuffer;
  54. };
  55. })();