| 82 | #reader = new BufferReader() |
| 83 | |
| 84 | public parse(buffer: BufferParameter, callback: MessageCallback) { |
| 85 | this.#mergeBuffer( |
| 86 | ArrayBuffer.isView(buffer) |
| 87 | ? buffer.buffer.slice( |
| 88 | buffer.byteOffset, |
| 89 | buffer.byteOffset + buffer.byteLength, |
| 90 | ) |
| 91 | : buffer, |
| 92 | ) |
| 93 | const bufferFullLength = this.#bufferOffset + this.#bufferRemainingLength |
| 94 | let offset = this.#bufferOffset |
| 95 | while (offset + HEADER_LENGTH <= bufferFullLength) { |
| 96 | // code is 1 byte long - it identifies the message type |
| 97 | const code = this.#bufferView.getUint8(offset) |
| 98 | // length is 1 Uint32BE - it is the length of the message EXCLUDING the code |
| 99 | const length = this.#bufferView.getUint32(offset + CODE_LENGTH, false) |
| 100 | const fullMessageLength = CODE_LENGTH + length |
| 101 | if (fullMessageLength + offset <= bufferFullLength) { |
| 102 | const message = this.#handlePacket( |
| 103 | offset + HEADER_LENGTH, |
| 104 | code, |
| 105 | length, |
| 106 | this.#bufferView.buffer, |
| 107 | ) |
| 108 | callback(message) |
| 109 | offset += fullMessageLength |
| 110 | } else { |
| 111 | break |
| 112 | } |
| 113 | } |
| 114 | if (offset === bufferFullLength) { |
| 115 | // No more use for the buffer |
| 116 | this.#bufferView = new DataView(emptyBuffer) |
| 117 | this.#bufferRemainingLength = 0 |
| 118 | this.#bufferOffset = 0 |
| 119 | } else { |
| 120 | // Adjust the cursors of remainingBuffer |
| 121 | this.#bufferRemainingLength = bufferFullLength - offset |
| 122 | this.#bufferOffset = offset |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | #mergeBuffer(buffer: ArrayBuffer): void { |
| 127 | if (this.#bufferRemainingLength > 0) { |