createToBase64.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createToBase64 = void 0;
  4. const flatstr_1 = require("./util/strings/flatstr");
  5. const constants_1 = require("./constants");
  6. const createToBase64 = (chars = constants_1.alphabet, pad = '=') => {
  7. if (chars.length !== 64)
  8. throw new Error('chars must be 64 characters long');
  9. const table = chars.split('');
  10. const table2 = [];
  11. for (const c1 of table) {
  12. for (const c2 of table) {
  13. const two = (0, flatstr_1.flatstr)(c1 + c2);
  14. table2.push(two);
  15. }
  16. }
  17. const E = pad;
  18. const EE = (0, flatstr_1.flatstr)(pad + pad);
  19. return (uint8, length) => {
  20. let out = '';
  21. const extraLength = length % 3;
  22. const baseLength = length - extraLength;
  23. for (let i = 0; i < baseLength; i += 3) {
  24. const o1 = uint8[i];
  25. const o2 = uint8[i + 1];
  26. const o3 = uint8[i + 2];
  27. const v1 = (o1 << 4) | (o2 >> 4);
  28. const v2 = ((o2 & 0b1111) << 8) | o3;
  29. out += table2[v1] + table2[v2];
  30. }
  31. if (!extraLength)
  32. return out;
  33. if (extraLength === 1) {
  34. const o1 = uint8[baseLength];
  35. out += table2[o1 << 4] + EE;
  36. }
  37. else {
  38. const o1 = uint8[baseLength];
  39. const o2 = uint8[baseLength + 1];
  40. const v1 = (o1 << 4) | (o2 >> 4);
  41. const v2 = (o2 & 0b1111) << 2;
  42. out += table2[v1] + table[v2] + E;
  43. }
  44. return out;
  45. };
  46. };
  47. exports.createToBase64 = createToBase64;
  48. //# sourceMappingURL=createToBase64.js.map