CborEncoder.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.CborEncoder = void 0;
  4. const isFloat32_1 = require("@jsonjoy.com/util/lib/buffers/isFloat32");
  5. const JsonPackExtension_1 = require("../JsonPackExtension");
  6. const CborEncoderFast_1 = require("./CborEncoderFast");
  7. const JsonPackValue_1 = require("../JsonPackValue");
  8. class CborEncoder extends CborEncoderFast_1.CborEncoderFast {
  9. writeUnknown(value) {
  10. this.writeNull();
  11. }
  12. writeAny(value) {
  13. switch (typeof value) {
  14. case 'number':
  15. return this.writeNumber(value);
  16. case 'string':
  17. return this.writeStr(value);
  18. case 'boolean':
  19. return this.writer.u8(0xf4 + +value);
  20. case 'object': {
  21. if (!value)
  22. return this.writer.u8(0xf6);
  23. const constructor = value.constructor;
  24. switch (constructor) {
  25. case Object:
  26. return this.writeObj(value);
  27. case Array:
  28. return this.writeArr(value);
  29. case Uint8Array:
  30. return this.writeBin(value);
  31. case Map:
  32. return this.writeMap(value);
  33. case JsonPackExtension_1.JsonPackExtension:
  34. return this.writeTag(value.tag, value.val);
  35. case JsonPackValue_1.JsonPackValue:
  36. const buf = value.val;
  37. return this.writer.buf(buf, buf.length);
  38. default:
  39. if (value instanceof Uint8Array)
  40. return this.writeBin(value);
  41. if (Array.isArray(value))
  42. return this.writeArr(value);
  43. if (value instanceof Map)
  44. return this.writeMap(value);
  45. return this.writeUnknown(value);
  46. }
  47. }
  48. case 'undefined':
  49. return this.writeUndef();
  50. case 'bigint':
  51. return this.writeBigInt(value);
  52. default:
  53. return this.writeUnknown(value);
  54. }
  55. }
  56. writeFloat(float) {
  57. if ((0, isFloat32_1.isFloat32)(float))
  58. this.writer.u8f32(0xfa, float);
  59. else
  60. this.writer.u8f64(0xfb, float);
  61. }
  62. writeMap(map) {
  63. this.writeMapHdr(map.size);
  64. map.forEach((value, key) => {
  65. this.writeAny(key);
  66. this.writeAny(value);
  67. });
  68. }
  69. writeUndef() {
  70. this.writer.u8(0xf7);
  71. }
  72. }
  73. exports.CborEncoder = CborEncoder;
  74. //# sourceMappingURL=CborEncoder.js.map