Skip to content

Commit 7043ee0

Browse files
committed
uasyncio: Implement StreamReader.readexactly().
With a unit test.
1 parent ec7b4b9 commit 7043ee0

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

uasyncio/test_readexactly.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from uasyncio import StreamReader
2+
3+
class MockSock:
4+
5+
def __init__(self, data_list):
6+
self.data = data_list
7+
8+
def read(self, sz):
9+
try:
10+
return self.data.pop(0)
11+
except IndexError:
12+
return b""
13+
14+
15+
mock = MockSock([
16+
b"123",
17+
b"234", b"5",
18+
b"a", b"b", b"c", b"d", b"e",
19+
])
20+
21+
22+
def func():
23+
sr = StreamReader(mock)
24+
assert await sr.readexactly(3) == b"123"
25+
assert await sr.readexactly(4) == b"2345"
26+
assert await sr.readexactly(5) == b"abcde"
27+
# This isn't how it should be, but the current behavior
28+
assert await sr.readexactly(10) == b""
29+
30+
for i in func():
31+
pass

uasyncio/uasyncio/__init__.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,19 @@ def read(self, n=-1):
8989
yield IOReadDone(self.s)
9090
return res
9191

92+
def readexactly(self, n):
93+
buf = b""
94+
while n:
95+
yield IORead(self.s)
96+
res = self.s.read(n)
97+
assert res is not None
98+
if not res:
99+
yield IOReadDone(self.s)
100+
break
101+
buf += res
102+
n -= len(res)
103+
return buf
104+
92105
def readline(self):
93106
if __debug__:
94107
log.debug("StreamReader.readline()")

0 commit comments

Comments
 (0)