createToBase64BinUint8.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createToBase64BinUint8 = void 0;
  4. const constants_1 = require("./constants");
  5. const createToBase64BinUint8 = (chars = constants_1.alphabet, pad = '=') => {
  6. if (chars.length !== 64)
  7. throw new Error('chars must be 64 characters long');
  8. const table = chars.split('').map((c) => c.charCodeAt(0));
  9. const table2 = [];
  10. for (const c1 of table) {
  11. for (const c2 of table) {
  12. const two = (c1 << 8) + c2;
  13. table2.push(two);
  14. }
  15. }
  16. const PAD = pad.length === 1 ? pad.charCodeAt(0) : 0;
  17. return (uint8, start, length, dest, offset) => {
  18. const extraLength = length % 3;
  19. const baseLength = length - extraLength;
  20. for (; start < baseLength; start += 3) {
  21. const o1 = uint8[start];
  22. const o2 = uint8[start + 1];
  23. const o3 = uint8[start + 2];
  24. const v1 = (o1 << 4) | (o2 >> 4);
  25. const v2 = ((o2 & 0b1111) << 8) | o3;
  26. let u16 = table2[v1];
  27. dest[offset++] = u16 >> 8;
  28. dest[offset++] = u16;
  29. u16 = table2[v2];
  30. dest[offset++] = u16 >> 8;
  31. dest[offset++] = u16;
  32. }
  33. if (extraLength === 1) {
  34. const o1 = uint8[baseLength];
  35. const u16 = table2[o1 << 4];
  36. dest[offset++] = u16 >> 8;
  37. dest[offset++] = u16;
  38. if (PAD) {
  39. dest[offset++] = PAD;
  40. dest[offset++] = PAD;
  41. }
  42. }
  43. else if (extraLength) {
  44. const o1 = uint8[baseLength];
  45. const o2 = uint8[baseLength + 1];
  46. const v1 = (o1 << 4) | (o2 >> 4);
  47. const v2 = (o2 & 0b1111) << 2;
  48. const u16 = table2[v1];
  49. dest[offset++] = u16 >> 8;
  50. dest[offset++] = u16;
  51. dest[offset++] = table[v2];
  52. if (PAD)
  53. dest[offset++] = PAD;
  54. }
  55. return offset;
  56. };
  57. };
  58. exports.createToBase64BinUint8 = createToBase64BinUint8;
  59. //# sourceMappingURL=createToBase64BinUint8.js.map