From 48df1f373f467553ee81acda9a990b47baf9698a Mon Sep 17 00:00:00 2001 From: Marin Petrunic Date: Tue, 20 Sep 2022 15:01:43 +0200 Subject: [PATCH] fix: optimize stream sink for small messages --- src/stream.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/stream.ts b/src/stream.ts index 867cc59..bfc29cf 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -174,17 +174,21 @@ export function createStream (options: Options): MplexStream { const uint8ArrayList = new Uint8ArrayList() for await (const data of source) { - uint8ArrayList.append(data) - - while (uint8ArrayList.length !== 0) { - if (uint8ArrayList.length <= maxMsgSize) { - send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() }) - uint8ArrayList.consume(uint8ArrayList.length) - break + if (data.length <= maxMsgSize) { + send({ id, type: Types.MESSAGE, data: data instanceof Uint8ArrayList ? data : new Uint8ArrayList(data) }) + } else { + uint8ArrayList.append(data) + + while (uint8ArrayList.length !== 0) { + // eslint-disable-next-line max-depth + if (uint8ArrayList.length <= maxMsgSize) { + send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() }) + uint8ArrayList.consume(uint8ArrayList.length) + break + } + send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) }) + uint8ArrayList.consume(maxMsgSize) } - - send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) }) - uint8ArrayList.consume(maxMsgSize) } } } catch (err: any) {