| 124 | } |
| 125 | |
| 126 | #mergeBuffer(buffer: ArrayBuffer): void { |
| 127 | if (this.#bufferRemainingLength > 0) { |
| 128 | const newLength = this.#bufferRemainingLength + buffer.byteLength |
| 129 | const newFullLength = newLength + this.#bufferOffset |
| 130 | if (newFullLength > this.#bufferView.byteLength) { |
| 131 | // We can't concat the new buffer with the remaining one |
| 132 | let newBuffer: ArrayBuffer |
| 133 | if ( |
| 134 | newLength <= this.#bufferView.byteLength && |
| 135 | this.#bufferOffset >= this.#bufferRemainingLength |
| 136 | ) { |
| 137 | // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer |
| 138 | newBuffer = this.#bufferView.buffer |
| 139 | } else { |
| 140 | // Allocate a new larger buffer |
| 141 | let newBufferLength = this.#bufferView.byteLength * 2 |
| 142 | while (newLength >= newBufferLength) { |
| 143 | newBufferLength *= 2 |
| 144 | } |
| 145 | newBuffer = new ArrayBuffer(newBufferLength) |
| 146 | } |
| 147 | // Move the remaining buffer to the new one |
| 148 | new Uint8Array(newBuffer).set( |
| 149 | new Uint8Array( |
| 150 | this.#bufferView.buffer, |
| 151 | this.#bufferOffset, |
| 152 | this.#bufferRemainingLength, |
| 153 | ), |
| 154 | ) |
| 155 | this.#bufferView = new DataView(newBuffer) |
| 156 | this.#bufferOffset = 0 |
| 157 | } |
| 158 | |
| 159 | // Concat the new buffer with the remaining one |
| 160 | new Uint8Array(this.#bufferView.buffer).set( |
| 161 | new Uint8Array(buffer), |
| 162 | this.#bufferOffset + this.#bufferRemainingLength, |
| 163 | ) |
| 164 | this.#bufferRemainingLength = newLength |
| 165 | } else { |
| 166 | this.#bufferView = new DataView(buffer) |
| 167 | this.#bufferOffset = 0 |
| 168 | this.#bufferRemainingLength = buffer.byteLength |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | #handlePacket( |
| 173 | offset: number, |