From c49514754bb90598517e1d31dca0d317414646f8 Mon Sep 17 00:00:00 2001 From: Roman Zeyde Date: Fri, 19 Feb 2016 11:34:20 +0200 Subject: [PATCH] util: add docstrings --- trezor_agent/tests/test_utils.py | 2 +- trezor_agent/util.py | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/trezor_agent/tests/test_utils.py b/trezor_agent/tests/test_utils.py index 26f66a9..b86cba1 100644 --- a/trezor_agent/tests/test_utils.py +++ b/trezor_agent/tests/test_utils.py @@ -38,7 +38,7 @@ class FakeSocket(object): def test_send_recv(): s = FakeSocket() util.send(s, b'123') - util.send(s, data=[42], fmt='B') + util.send(s, b'*') assert s.buf.getvalue() == b'123*' s.buf.seek(0) diff --git a/trezor_agent/util.py b/trezor_agent/util.py index b17675f..8e0e29b 100644 --- a/trezor_agent/util.py +++ b/trezor_agent/util.py @@ -1,14 +1,20 @@ +"""Various I/O and serialization utilities.""" import io import struct -def send(conn, data, fmt=None): - if fmt: - data = struct.pack(fmt, *data) +def send(conn, data): + """Send data blob to connection socket.""" conn.sendall(data) def recv(conn, size): + """ + Receive bytes from connection socket or stream. + + If size is struct.calcsize()-compatible format, use it to unpack the data. + Otherwise, return the plain blob as bytes. + """ try: fmt = size size = struct.calcsize(fmt) @@ -34,11 +40,13 @@ def recv(conn, size): def read_frame(conn): + """Read size-prefixed frame from connection.""" size, = recv(conn, '>L') return recv(conn, size) def bytes2num(s): + """Convert MSB-first bytes to an unsigned integer.""" res = 0 for i, c in enumerate(reversed(bytearray(s))): res += c << (i * 8) @@ -46,6 +54,7 @@ def bytes2num(s): def num2bytes(value, size): + """Convert an unsigned integer to MSB-first bytes with specified size.""" res = [] for _ in range(size): res.append(value & 0xFF) @@ -55,10 +64,12 @@ def num2bytes(value, size): def pack(fmt, *args): + """Serialize MSB-first message.""" return struct.pack('>' + fmt, *args) def frame(*msgs): + """Serialize MSB-first length-prefixed frame.""" res = io.BytesIO() for msg in msgs: res.write(msg)