From b59c5d6ca11c8767a152a910666828f575644fc3 Mon Sep 17 00:00:00 2001 From: Alex Stokes Date: Thu, 22 Aug 2019 17:54:49 +0200 Subject: [PATCH] Add "msgio" functions --- libp2p/io/__init__.py | 0 libp2p/io/msgio.py | 16 ++++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 libp2p/io/__init__.py create mode 100644 libp2p/io/msgio.py diff --git a/libp2p/io/__init__.py b/libp2p/io/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/libp2p/io/msgio.py b/libp2p/io/msgio.py new file mode 100644 index 0000000..6ad11bc --- /dev/null +++ b/libp2p/io/msgio.py @@ -0,0 +1,16 @@ +import asyncio + +SIZE_LEN_BYTES = 4 + +# TODO unify w/ https://github.com/libp2p/py-libp2p/blob/1aed52856f56a4b791696bbcbac31b5f9c2e88c9/libp2p/utils.py#L85-L99 + + +def encode(msg_bytes: bytes) -> bytes: + len_prefix = len(msg_bytes).to_bytes(SIZE_LEN_BYTES, "big") + return len_prefix + msg_bytes + + +async def read_next_message(reader: asyncio.StreamReader) -> bytes: + len_bytes = await reader.readexactly(SIZE_LEN_BYTES) + len_int = int.from_bytes(len_bytes, "big") + return await reader.readexactly(len_int)