kopia lustrzana https://github.com/micropython/micropython-lib
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.pull/149/head
rodzic
a8d85e28d0
commit
ec7b4b948b
|
@ -0,0 +1,30 @@
|
||||||
|
from uasyncio import StreamReader
|
||||||
|
|
||||||
|
class MockSock:
|
||||||
|
|
||||||
|
def __init__(self, data_list):
|
||||||
|
self.data = data_list
|
||||||
|
|
||||||
|
def readline(self):
|
||||||
|
try:
|
||||||
|
return self.data.pop(0)
|
||||||
|
except IndexError:
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
mock = MockSock([
|
||||||
|
b"line1\n",
|
||||||
|
b"parts ", b"of ", b"line2\n",
|
||||||
|
b"unterminated",
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def func():
|
||||||
|
sr = StreamReader(mock)
|
||||||
|
assert await sr.readline() == b"line1\n"
|
||||||
|
assert await sr.readline() == b"parts of line2\n"
|
||||||
|
assert await sr.readline() == b"unterminated"
|
||||||
|
assert await sr.readline() == b""
|
||||||
|
|
||||||
|
for i in func():
|
||||||
|
pass
|
|
@ -92,19 +92,20 @@ class StreamReader:
|
||||||
def readline(self):
|
def readline(self):
|
||||||
if __debug__:
|
if __debug__:
|
||||||
log.debug("StreamReader.readline()")
|
log.debug("StreamReader.readline()")
|
||||||
# if DEBUG and __debug__:
|
buf = b""
|
||||||
# log.debug("StreamReader.readline(): after IORead: %s", s)
|
|
||||||
while True:
|
while True:
|
||||||
yield IORead(self.s)
|
yield IORead(self.s)
|
||||||
res = self.s.readline()
|
res = self.s.readline()
|
||||||
if res is not None:
|
assert res is not None
|
||||||
break
|
|
||||||
log.warn("Empty read")
|
|
||||||
if not res:
|
if not res:
|
||||||
yield IOReadDone(self.s)
|
yield IOReadDone(self.s)
|
||||||
|
break
|
||||||
|
buf += res
|
||||||
|
if buf[-1] == 0x0a:
|
||||||
|
break
|
||||||
if DEBUG and __debug__:
|
if DEBUG and __debug__:
|
||||||
log.debug("StreamReader.readline(): res: %s", res)
|
log.debug("StreamReader.readline(): %s", buf)
|
||||||
return res
|
return buf
|
||||||
|
|
||||||
def aclose(self):
|
def aclose(self):
|
||||||
yield IOReadDone(self.s)
|
yield IOReadDone(self.s)
|
||||||
|
|
Ładowanie…
Reference in New Issue