From 0bc1ffa1b3ab590b06cc172a86b5a185324e878c Mon Sep 17 00:00:00 2001 From: David Kerkeslager Date: Sun, 9 Oct 2016 19:27:50 -0400 Subject: [PATCH] Binary object serialization --- serial/serial/binary.py | 20 +++++++++++++++++++- serial/test.py | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/serial/serial/binary.py b/serial/serial/binary.py index dd1b990..444db4f 100644 --- a/serial/serial/binary.py +++ b/serial/serial/binary.py @@ -62,7 +62,25 @@ def _serialize_list(to): return struct.pack(fmt, tags.LIST, list_tag, len(payload)) + payload def _serialize_object(to): - raise Exception('Not implemented') + assert isinstance(to.instance, list) + + # TODO Actually handle this case somehow + assert len(to.instance) > 0 + + # TODO Do this a better way + serialized_kvps = [(serialize(k), serialize(v)) for k,v in to.instance] + key_type_tag = serialized_kvps[0][0][0] + + def check_and_strip_prefix(b): + item_tag = b[0] + assert key_type_tag == item_tag + return b[1:] + + payload = b''.join(check_and_strip_prefix(k) + v for k,v in serialized_kvps) + + fmt = '!BBI' + + return struct.pack(fmt, tags.OBJECT, key_type_tag, len(payload)) + payload _TAGS_TO_SERIALIZERS = { tags.NULL: _make_tag_only_serializer(tags.NULL, None), diff --git a/serial/test.py b/serial/test.py index 72c7b35..ca80671 100644 --- a/serial/test.py +++ b/serial/test.py @@ -67,7 +67,7 @@ EXAMPLE_BINARY_REPRESENTATIONS = [ ), ], ), - b'\x32\x21\x00\x00\x00\x03foo\x21\x00\x00\x00\x03bar\x00\x00\x00\x03baz\x03\x2a', + b'\x32\x21\x00\x00\x00\x18\x00\x00\x00\x03foo\x21\x00\x00\x00\x03bar\x00\x00\x00\x03baz\x03\x2a', ), ] -- 2.20.1