Introduces IO abstractions apart from asyncio or those attached to IRawConnection

Also adds `msgio` utilities to mirror the Go implementation
This commit is contained in:
Alex Stokes
2019-09-03 21:42:45 -07:00
parent cd3e093001
commit 8e8318aa5c
7 changed files with 154 additions and 32 deletions

21
libp2p/io/utils.py Normal file
View File

@ -0,0 +1,21 @@
from libp2p.io.abc import Reader
from libp2p.io.exceptions import IncompleteReadError
DEFAULT_RETRY_READ_COUNT = 100
async def read_exactly(
reader: Reader, n: int, retry_count: int = DEFAULT_RETRY_READ_COUNT
) -> bytes:
"""
NOTE: relying on exceptions to break out on erroneous conditions, like EOF
"""
data = await reader.read(n)
for _ in range(retry_count):
if len(data) < n:
remaining = n - len(data)
data += await reader.read(remaining)
else:
return data
raise IncompleteReadError({"requested_count": n, "received_count": len(data)})