* @param {Buffer} chunk
(chunk)
| 311 | * @param {Buffer} chunk |
| 312 | */ |
| 313 | execute (chunk) { |
| 314 | assert(currentParser === null) |
| 315 | assert(this.ptr != null) |
| 316 | assert(!this.paused) |
| 317 | |
| 318 | const { socket, llhttp } = this |
| 319 | |
| 320 | // Allocate a new buffer if the current buffer is too small. |
| 321 | if (chunk.length > currentBufferSize) { |
| 322 | if (currentBufferPtr) { |
| 323 | llhttp.free(currentBufferPtr) |
| 324 | } |
| 325 | // Allocate a buffer that is a multiple of 4096 bytes. |
| 326 | currentBufferSize = Math.ceil(chunk.length / 4096) * 4096 |
| 327 | currentBufferPtr = llhttp.malloc(currentBufferSize) |
| 328 | } |
| 329 | |
| 330 | if ( |
| 331 | currentBuffer === null || |
| 332 | currentBuffer.buffer !== llhttp.memory.buffer || |
| 333 | currentBuffer.byteOffset !== currentBufferPtr || |
| 334 | currentBuffer.byteLength !== currentBufferSize |
| 335 | ) { |
| 336 | currentBuffer = new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize) |
| 337 | } |
| 338 | |
| 339 | currentBuffer.set(chunk) |
| 340 | |
| 341 | // Call `execute` on the wasm parser. |
| 342 | // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, |
| 343 | // and finally the length of bytes to parse. |
| 344 | // The return value is an error code or `constants.ERROR.OK`. |
| 345 | try { |
| 346 | let ret |
| 347 | |
| 348 | try { |
| 349 | currentBufferRef = chunk |
| 350 | currentParser = this |
| 351 | ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length) |
| 352 | } finally { |
| 353 | currentParser = null |
| 354 | currentBufferRef = null |
| 355 | } |
| 356 | |
| 357 | if (ret !== constants.ERROR.OK) { |
| 358 | const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr) |
| 359 | |
| 360 | if (ret === constants.ERROR.PAUSED_UPGRADE) { |
| 361 | this.onUpgrade(data) |
| 362 | } else if (ret === constants.ERROR.PAUSED) { |
| 363 | this.paused = true |
| 364 | socket.unshift(data) |
| 365 | } else { |
| 366 | throw this.createError(ret, data) |
| 367 | } |
| 368 | } |
| 369 | } catch (err) { |
| 370 | util.destroy(socket, err) |