decoder.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.SlipDecoder = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * A transform stream that decodes slip encoded data.
  7. * @extends Transform
  8. *
  9. * Runs in O(n) time, stripping out slip encoding and emitting decoded data. Optionally custom slip escape and delimiters can be provided.
  10. */
  11. class SlipDecoder extends stream_1.Transform {
  12. opts;
  13. buffer;
  14. escape;
  15. start;
  16. constructor(options = {}) {
  17. super(options);
  18. const { START, ESC = 0xdb, END = 0xc0, ESC_START, ESC_END = 0xdc, ESC_ESC = 0xdd } = options;
  19. this.opts = {
  20. START,
  21. ESC,
  22. END,
  23. ESC_START,
  24. ESC_END,
  25. ESC_ESC,
  26. };
  27. this.buffer = Buffer.alloc(0);
  28. this.escape = false;
  29. this.start = false;
  30. }
  31. _transform(chunk, encoding, cb) {
  32. for (let ndx = 0; ndx < chunk.length; ndx++) {
  33. let byte = chunk[ndx];
  34. if (byte === this.opts.START) {
  35. this.start = true;
  36. continue;
  37. }
  38. else if (undefined == this.opts.START) {
  39. this.start = true;
  40. }
  41. if (this.escape) {
  42. if (byte === this.opts.ESC_START && this.opts.START) {
  43. byte = this.opts.START;
  44. }
  45. else if (byte === this.opts.ESC_ESC) {
  46. byte = this.opts.ESC;
  47. }
  48. else if (byte === this.opts.ESC_END) {
  49. byte = this.opts.END;
  50. }
  51. else {
  52. this.escape = false;
  53. this.push(this.buffer);
  54. this.buffer = Buffer.alloc(0);
  55. }
  56. }
  57. else {
  58. if (byte === this.opts.ESC) {
  59. this.escape = true;
  60. continue;
  61. }
  62. if (byte === this.opts.END) {
  63. this.push(this.buffer);
  64. this.buffer = Buffer.alloc(0);
  65. this.escape = false;
  66. this.start = false;
  67. continue;
  68. }
  69. }
  70. this.escape = false;
  71. if (this.start) {
  72. this.buffer = Buffer.concat([this.buffer, Buffer.from([byte])]);
  73. }
  74. }
  75. cb();
  76. }
  77. _flush(cb) {
  78. this.push(this.buffer);
  79. this.buffer = Buffer.alloc(0);
  80. cb();
  81. }
  82. }
  83. exports.SlipDecoder = SlipDecoder;