(buffer: Buffer, callback: MessageCallback)
| 92 | } |
| 93 | |
| 94 | public parse(buffer: Buffer, callback: MessageCallback) { |
| 95 | this.mergeBuffer(buffer) |
| 96 | const bufferFullLength = this.bufferOffset + this.bufferLength |
| 97 | let offset = this.bufferOffset |
| 98 | while (offset + HEADER_LENGTH <= bufferFullLength) { |
| 99 | // code is 1 byte long - it identifies the message type |
| 100 | const code = this.buffer[offset] |
| 101 | // length is 1 Uint32BE - it is the length of the message EXCLUDING the code |
| 102 | const length = this.buffer.readUInt32BE(offset + CODE_LENGTH) |
| 103 | const fullMessageLength = CODE_LENGTH + length |
| 104 | if (fullMessageLength + offset <= bufferFullLength) { |
| 105 | const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer) |
| 106 | callback(message) |
| 107 | offset += fullMessageLength |
| 108 | } else { |
| 109 | break |
| 110 | } |
| 111 | } |
| 112 | if (offset === bufferFullLength) { |
| 113 | // No more use for the buffer |
| 114 | this.buffer = emptyBuffer |
| 115 | this.bufferLength = 0 |
| 116 | this.bufferOffset = 0 |
| 117 | } else { |
| 118 | // Adjust the cursors of remainingBuffer |
| 119 | this.bufferLength = bufferFullLength - offset |
| 120 | this.bufferOffset = offset |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | private mergeBuffer(buffer: Buffer): void { |
| 125 | if (this.bufferLength > 0) { |
no test coverage detected