Skip to content

Commit ec7b4b9

Browse files
committed
uasyncio: StreamReader.readline: Handle partial reads.
Now it will return a complete line regardless if it may take several partial reads to do that. Test included.
1 parent a8d85e2 commit ec7b4b9

File tree

2 files changed

+39
-8
lines changed

2 files changed

+39
-8
lines changed

uasyncio/test_readline.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from uasyncio import StreamReader
2+
3+
class MockSock:
4+
5+
def __init__(self, data_list):
6+
self.data = data_list
7+
8+
def readline(self):
9+
try:
10+
return self.data.pop(0)
11+
except IndexError:
12+
return b""
13+
14+
15+
mock = MockSock([
16+
b"line1\n",
17+
b"parts ", b"of ", b"line2\n",
18+
b"unterminated",
19+
])
20+
21+
22+
def func():
23+
sr = StreamReader(mock)
24+
assert await sr.readline() == b"line1\n"
25+
assert await sr.readline() == b"parts of line2\n"
26+
assert await sr.readline() == b"unterminated"
27+
assert await sr.readline() == b""
28+
29+
for i in func():
30+
pass

uasyncio/uasyncio/__init__.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,19 +92,20 @@ def read(self, n=-1):
9292
def readline(self):
9393
if __debug__:
9494
log.debug("StreamReader.readline()")
95-
# if DEBUG and __debug__:
96-
# log.debug("StreamReader.readline(): after IORead: %s", s)
95+
buf = b""
9796
while True:
9897
yield IORead(self.s)
9998
res = self.s.readline()
100-
if res is not None:
99+
assert res is not None
100+
if not res:
101+
yield IOReadDone(self.s)
102+
break
103+
buf += res
104+
if buf[-1] == 0x0a:
101105
break
102-
log.warn("Empty read")
103-
if not res:
104-
yield IOReadDone(self.s)
105106
if DEBUG and __debug__:
106-
log.debug("StreamReader.readline(): res: %s", res)
107-
return res
107+
log.debug("StreamReader.readline(): %s", buf)
108+
return buf
108109

109110
def aclose(self):
110111
yield IOReadDone(self.s)

0 commit comments

Comments
 (0)