base64-arraybuffer.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(chars){
  9. "use strict";
  10. exports.encode = function(arraybuffer) {
  11. var bytes = new Uint8Array(arraybuffer),
  12. i, len = bytes.length, base64 = "";
  13. for (i = 0; i < len; i+=3) {
  14. base64 += chars[bytes[i] >> 2];
  15. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  16. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  17. base64 += chars[bytes[i + 2] & 63];
  18. }
  19. if ((len % 3) === 2) {
  20. base64 = base64.substring(0, base64.length - 1) + "=";
  21. } else if (len % 3 === 1) {
  22. base64 = base64.substring(0, base64.length - 2) + "==";
  23. }
  24. return base64;
  25. };
  26. exports.decode = function(base64) {
  27. var bufferLength = base64.length * 0.75,
  28. len = base64.length, i, p = 0,
  29. encoded1, encoded2, encoded3, encoded4;
  30. if (base64[base64.length - 1] === "=") {
  31. bufferLength--;
  32. if (base64[base64.length - 2] === "=") {
  33. bufferLength--;
  34. }
  35. }
  36. var arraybuffer = new ArrayBuffer(bufferLength),
  37. bytes = new Uint8Array(arraybuffer);
  38. for (i = 0; i < len; i+=4) {
  39. encoded1 = chars.indexOf(base64[i]);
  40. encoded2 = chars.indexOf(base64[i+1]);
  41. encoded3 = chars.indexOf(base64[i+2]);
  42. encoded4 = chars.indexOf(base64[i+3]);
  43. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  44. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  45. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  46. }
  47. return arraybuffer;
  48. };
  49. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");