Skip to content

Commit

Permalink
Merge pull request #12 from jfjlaros/until
Browse files Browse the repository at this point in the history
Added until generator for easier looping.
  • Loading branch information
jfjlaros committed Dec 22, 2020
2 parents 2bddeeb + adb9b0e commit bc0445d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
25 changes: 16 additions & 9 deletions simple_rpc/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,7 @@ def _read_bytes_until(stream, delimiter):
:returns bytes: Byte string.
"""
data = b''

while True:
char = stream.read(1)
if char == delimiter:
break
data += char

return data
return b''.join(until(lambda x: x == delimiter, stream.read, 1))


def _read_basic(stream, endianness, basic_type):
Expand Down Expand Up @@ -114,3 +106,18 @@ def write(stream, endianness, size_t, obj_type, obj):
write(stream, endianness, size_t, item_type, item)
else:
_write_basic(stream, endianness, obj_type, obj)


def until(condition, f, *args, **kwargs):
"""Call {f(*args, **kwargs)} until {condition} is true.
:arg callable condition: Function that inspects the result of {f}.
:arg callable f: Any function.
:arg list *args: Porisional arguments of {f}.
:arg dict **kwargs: Keyword arguments of {f}.
"""
while True:
result = f(*args, **kwargs)
if condition(result):
break
yield result
9 changes: 3 additions & 6 deletions simple_rpc/simple_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from serial.serialutil import SerialException

from .extras import make_function
from .io import read, read_byte_string, write
from .io import read, read_byte_string, until, write
from .protocol import parse_line


Expand Down Expand Up @@ -94,13 +94,10 @@ def _get_methods(self):
bytes([c]) for c in self._read_byte_string())

methods = {}
index = 0
line = self._read_byte_string()
while line:
for index, line in enumerate(
until(lambda x: x == b'', self._read_byte_string)):
method = parse_line(index, line)
methods[method['name']] = method
line = self._read_byte_string()
index += 1

return methods

Expand Down

0 comments on commit bc0445d

Please sign in to comment.