base64-arraybuffer.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2. // Use a lookup table to find the index.
  3. const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  4. for (let i = 0; i < chars.length; i++) {
  5. lookup[chars.charCodeAt(i)] = i;
  6. }
  7. export const encode = (arraybuffer) => {
  8. let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
  9. for (i = 0; i < len; i += 3) {
  10. base64 += chars[bytes[i] >> 2];
  11. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  12. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  13. base64 += chars[bytes[i + 2] & 63];
  14. }
  15. if (len % 3 === 2) {
  16. base64 = base64.substring(0, base64.length - 1) + '=';
  17. }
  18. else if (len % 3 === 1) {
  19. base64 = base64.substring(0, base64.length - 2) + '==';
  20. }
  21. return base64;
  22. };
  23. export const decode = (base64) => {
  24. let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
  25. if (base64[base64.length - 1] === '=') {
  26. bufferLength--;
  27. if (base64[base64.length - 2] === '=') {
  28. bufferLength--;
  29. }
  30. }
  31. const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
  32. for (i = 0; i < len; i += 4) {
  33. encoded1 = lookup[base64.charCodeAt(i)];
  34. encoded2 = lookup[base64.charCodeAt(i + 1)];
  35. encoded3 = lookup[base64.charCodeAt(i + 2)];
  36. encoded4 = lookup[base64.charCodeAt(i + 3)];
  37. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  38. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  39. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  40. }
  41. return arraybuffer;
  42. };