ParseFileEncode.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. /* eslint-disable no-bitwise */
  3. function b64Digit(number
  4. /*: number*/
  5. )
  6. /*: string*/
  7. {
  8. if (number < 26) {
  9. return String.fromCharCode(65 + number);
  10. }
  11. if (number < 52) {
  12. return String.fromCharCode(97 + (number - 26));
  13. }
  14. if (number < 62) {
  15. return String.fromCharCode(48 + (number - 52));
  16. }
  17. if (number === 62) {
  18. return '+';
  19. }
  20. if (number === 63) {
  21. return '/';
  22. }
  23. throw new TypeError("Tried to encode large digit ".concat(number, " in base64."));
  24. }
  25. function encodeBase64(bytes
  26. /*: Array<number>*/
  27. )
  28. /*: string*/
  29. {
  30. var chunks = [];
  31. chunks.length = Math.ceil(bytes.length / 3);
  32. for (var i = 0; i < chunks.length; i++) {
  33. var b1 = bytes[i * 3];
  34. var b2 = bytes[i * 3 + 1] || 0;
  35. var b3 = bytes[i * 3 + 2] || 0;
  36. var has2 = i * 3 + 1 < bytes.length;
  37. var has3 = i * 3 + 2 < bytes.length;
  38. chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
  39. }
  40. return chunks.join('');
  41. }
  42. module.exports = {
  43. encodeBase64: encodeBase64,
  44. b64Digit: b64Digit
  45. };