encode.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.encode = exports.encodeTe = exports.encodeNative = exports.encodeFrom = exports.encodeUtf8Write = void 0;
  4. const hasBuffer = typeof Buffer !== undefined;
  5. const utf8Write = hasBuffer
  6. ? Buffer.prototype.utf8Write
  7. : null;
  8. const from = hasBuffer ? Buffer.from : null;
  9. const encodeUtf8Write = (arr, str, pos, maxLength) => utf8Write.call(arr, str, pos, maxLength);
  10. exports.encodeUtf8Write = encodeUtf8Write;
  11. const encodeFrom = (arr, str, pos, maxLength) => {
  12. const offset = arr.byteOffset + pos;
  13. const buf = from(arr.buffer).subarray(offset, offset + maxLength);
  14. return buf.write(str, 0, maxLength, 'utf8');
  15. };
  16. exports.encodeFrom = encodeFrom;
  17. const encodeNative = (arr, str, pos, maxLength) => {
  18. const length = str.length;
  19. const start = pos;
  20. let curr = 0;
  21. while (curr < length) {
  22. let value = str.charCodeAt(curr++);
  23. if ((value & 0xffffff80) === 0) {
  24. arr[pos++] = value;
  25. continue;
  26. }
  27. else if ((value & 0xfffff800) === 0) {
  28. arr[pos++] = ((value >> 6) & 0x1f) | 0xc0;
  29. }
  30. else {
  31. if (value >= 0xd800 && value <= 0xdbff) {
  32. if (curr < length) {
  33. const extra = str.charCodeAt(curr);
  34. if ((extra & 0xfc00) === 0xdc00) {
  35. curr++;
  36. value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
  37. }
  38. }
  39. }
  40. if ((value & 0xffff0000) === 0) {
  41. arr[pos++] = ((value >> 12) & 0x0f) | 0xe0;
  42. arr[pos++] = ((value >> 6) & 0x3f) | 0x80;
  43. }
  44. else {
  45. arr[pos++] = ((value >> 18) & 0x07) | 0xf0;
  46. arr[pos++] = ((value >> 12) & 0x3f) | 0x80;
  47. arr[pos++] = ((value >> 6) & 0x3f) | 0x80;
  48. }
  49. }
  50. arr[pos++] = (value & 0x3f) | 0x80;
  51. }
  52. return pos - start;
  53. };
  54. exports.encodeNative = encodeNative;
  55. const textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
  56. const encodeTe = (arr, str, pos, maxLength) => textEncoder.encodeInto(str, arr.subarray(pos, pos + maxLength)).written;
  57. exports.encodeTe = encodeTe;
  58. exports.encode = utf8Write ? exports.encodeUtf8Write : from ? exports.encodeFrom : exports.encodeNative;
  59. //# sourceMappingURL=encode.js.map