uasyncio: Implement StreamReader.readexactly().

With a unit test.
pull/149/head
Paul Sokolovsky 2017-01-28 01:04:21 +03:00
rodzic ec7b4b948b
commit 7043ee0702
2 zmienionych plików z 44 dodań i 0 usunięć

Wyświetl plik

@ -0,0 +1,31 @@
from uasyncio import StreamReader
class MockSock:
def __init__(self, data_list):
self.data = data_list
def read(self, sz):
try:
return self.data.pop(0)
except IndexError:
return b""
mock = MockSock([
b"123",
b"234", b"5",
b"a", b"b", b"c", b"d", b"e",
])
def func():
sr = StreamReader(mock)
assert await sr.readexactly(3) == b"123"
assert await sr.readexactly(4) == b"2345"
assert await sr.readexactly(5) == b"abcde"
# This isn't how it should be, but the current behavior
assert await sr.readexactly(10) == b""
for i in func():
pass

Wyświetl plik

@ -89,6 +89,19 @@ class StreamReader:
yield IOReadDone(self.s)
return res
def readexactly(self, n):
buf = b""
while n:
yield IORead(self.s)
res = self.s.read(n)
assert res is not None
if not res:
yield IOReadDone(self.s)
break
buf += res
n -= len(res)
return buf
def readline(self):
if __debug__:
log.debug("StreamReader.readline()")