From 91150588036fc3d8611f659fad063138e25b2cd8 Mon Sep 17 00:00:00 2001 From: bptato Date: Sun, 24 Mar 2024 12:04:46 +0100 Subject: bufreader: add initPacketReader --- src/io/bufreader.nim | 10 ++++++---- src/io/dynstream.nim | 7 +++++++ src/server/buffer.nim | 4 +--- 3 files changed, 14 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/io/bufreader.nim b/src/io/bufreader.nim index a8d30fb0..eca6b585 100644 --- a/src/io/bufreader.nim +++ b/src/io/bufreader.nim @@ -27,12 +27,14 @@ proc initReader*(stream: DynStream; len: int): BufferedReader = break return reader +proc initPacketReader*(stream: DynStream): BufferedReader = + var len: int + stream.recvDataLoop(addr len, sizeof(len)) + return stream.initReader(len) + template withPacketReader*(stream: DynStream; r, body: untyped) = block: - var len: int - # note: this must be readData - doAssert stream.readData(addr len, sizeof(len)) == sizeof(len) - var r = stream.initReader(len) + var r = stream.initPacketReader() body proc sread*(reader: var BufferedReader; n: var SomeNumber) diff --git a/src/io/dynstream.nim b/src/io/dynstream.nim index ac1269f5..10db4c64 100644 --- a/src/io/dynstream.nim +++ b/src/io/dynstream.nim @@ -46,6 +46,13 @@ proc sendDataLoop*(s: DynStream; buffer: pointer; len: int) = if n == len: break +proc recvDataLoop*(s: DynStream; buffer: pointer; len: int) = + var n = 0 + while true: + n += s.recvData(addr cast[ptr UncheckedArray[uint8]](buffer)[n], len - n) + if n == len: + break + proc dsClose(s: Stream) = DynStream(s).sclose() diff --git a/src/server/buffer.nim b/src/server/buffer.nim index bcc39aa2..e952d9aa 100644 --- a/src/server/buffer.nim +++ b/src/server/buffer.nim @@ -1791,11 +1791,9 @@ macro bufferDispatcher(funs: static ProxyMap; buffer: Buffer; return switch proc readCommand(buffer: Buffer) = + var r = buffer.pstream.initPacketReader() var cmd: BufferCommand - var len: int var packetid: int - buffer.pstream.sread(len) - var r = buffer.pstream.initReader(len) r.sread(cmd) r.sread(packetid) bufferDispatcher(ProxyFunctions, buffer, cmd, packetid, r) -- cgit 1.4.1-2-gfad0