From ffc3b04222e540ffa6e338c0615fb0a506dea813 Mon Sep 17 00:00:00 2001 From: Dmitriy Ryajov Date: Sat, 29 Feb 2020 17:20:18 +0100 Subject: [PATCH] read should await for data on an empty buff --- libp2p/stream/bufferstream.nim | 4 ++++ tests/testbufferstream.nim | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/libp2p/stream/bufferstream.nim b/libp2p/stream/bufferstream.nim index 681fb8e..d35a6ac 100644 --- a/libp2p/stream/bufferstream.nim +++ b/libp2p/stream/bufferstream.nim @@ -132,6 +132,10 @@ method read*(s: BufferStream, n = -1): Future[seq[byte]] {.async.} = ## var size = if n > 0: n else: s.readBuf.len() var index = 0 + + if s.readBuf.len() == 0: + await s.requestReadBytes() + while index < size: while s.readBuf.len() > 0 and index < size: result.add(s.popFirst()) diff --git a/tests/testbufferstream.nim b/tests/testbufferstream.nim index 2a02ca3..2ea0821 100644 --- a/tests/testbufferstream.nim +++ b/tests/testbufferstream.nim @@ -84,6 +84,29 @@ suite "BufferStream": check: waitFor(testRead()) == true + test "read all from small buffer": + proc testRead(): Future[bool] {.async.} = + proc writeHandler(data: seq[byte]) {.async, gcsafe.} = + discard + + let buff = newBufferStream(writeHandler, 4) + check buff.len == 0 + + proc reader() {.async.} = + var size = 0 + while size != 5: + var msg = await buff.read() + size += msg.len + check size == 5 + + var fut = reader() + await buff.pushTo(cast[seq[byte]](@"12345")) + await fut + result = true + + check: + waitFor(testRead()) == true + test "readExactly": proc testReadExactly(): Future[bool] {.async.} = proc writeHandler(data: seq[byte]) {.async, gcsafe.} = discard