CborEncoderStable.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CborEncoderStable = void 0;
  4. const CborEncoder_1 = require("./CborEncoder");
  5. const insertion2_1 = require("@jsonjoy.com/util/lib/sort/insertion2");
  6. const objKeyCmp_1 = require("@jsonjoy.com/util/lib/objKeyCmp");
  7. const strHeaderLength = (strSize) => {
  8. if (strSize <= 23)
  9. return 1;
  10. else if (strSize <= 0xff)
  11. return 2;
  12. else if (strSize <= 0xffff)
  13. return 3;
  14. else
  15. return 5;
  16. };
  17. class CborEncoderStable extends CborEncoder_1.CborEncoder {
  18. writeObj(obj) {
  19. const keys = Object.keys(obj);
  20. (0, insertion2_1.sort)(keys, objKeyCmp_1.objKeyCmp);
  21. const length = keys.length;
  22. this.writeObjHdr(length);
  23. for (let i = 0; i < length; i++) {
  24. const key = keys[i];
  25. this.writeStr(key);
  26. this.writeAny(obj[key]);
  27. }
  28. }
  29. writeStr(str) {
  30. const writer = this.writer;
  31. const length = str.length;
  32. const maxSize = length * 4;
  33. writer.ensureCapacity(5 + maxSize);
  34. const headerLengthGuess = strHeaderLength(length);
  35. const x0 = writer.x;
  36. const x1 = x0 + headerLengthGuess;
  37. writer.x = x1;
  38. const bytesWritten = writer.utf8(str);
  39. const uint8 = writer.uint8;
  40. const headerLength = strHeaderLength(bytesWritten);
  41. if (headerLength !== headerLengthGuess) {
  42. const shift = headerLength - headerLengthGuess;
  43. uint8.copyWithin(x1 + shift, x1, x1 + bytesWritten);
  44. }
  45. switch (headerLength) {
  46. case 1:
  47. uint8[x0] = 96 + bytesWritten;
  48. break;
  49. case 2:
  50. uint8[x0] = 0x78;
  51. uint8[x0 + 1] = bytesWritten;
  52. break;
  53. case 3: {
  54. uint8[x0] = 0x79;
  55. writer.view.setUint16(x0 + 1, bytesWritten);
  56. break;
  57. }
  58. case 5: {
  59. uint8[x0] = 0x7a;
  60. writer.view.setUint32(x0 + 1, bytesWritten);
  61. break;
  62. }
  63. }
  64. writer.x = x0 + headerLength + bytesWritten;
  65. }
  66. writeUndef() {
  67. this.writeNull();
  68. }
  69. }
  70. exports.CborEncoderStable = CborEncoderStable;
  71. //# sourceMappingURL=CborEncoderStable.js.map