From d5b18a84abc89a7e2c5db30639f8978eb5e8847d Mon Sep 17 00:00:00 2001 From: Pierre Ossman Date: Wed, 3 Sep 2025 11:24:34 +0200 Subject: [PATCH] Expose length of buffered WebSocket data Some encodings don't know how much data they need, rather they must probe the data stream until they find an end marker. Expose how much data is buffered in order to make this search efficient. --- core/websock.js | 4 ++++ tests/test.websock.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/core/websock.js b/core/websock.js index ae17a440..ee8a4bc4 100644 --- a/core/websock.js +++ b/core/websock.js @@ -124,6 +124,10 @@ export default class Websock { return res >>> 0; } + rQlen() { + return this._rQlen - this._rQi; + } + rQshiftStr(len) { let str = ""; // Handle large arrays in steps to avoid long strings on the stack diff --git a/tests/test.websock.js b/tests/test.websock.js index 62bcbfa5..110e6ad0 100644 --- a/tests/test.websock.js +++ b/tests/test.websock.js @@ -47,6 +47,20 @@ describe('Websock', function () { }); }); + describe('rQlen())', function () { + it('should return the number of buffered bytes in the receive queue', function () { + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + expect(sock.rQlen()).to.equal(8); + sock.rQshift8(); + expect(sock.rQlen()).to.equal(7); + sock.rQshift16(); + expect(sock.rQlen()).to.equal(5); + sock.rQshift32(); + expect(sock.rQlen()).to.equal(1); + }); + }); + describe('rQshiftStr', function () { it('should shift the given number of bytes off of the receive queue and return a string', function () { websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34,