From: David Kerkeslager Date: Sun, 9 Oct 2016 23:27:50 +0000 (-0400) Subject: Binary object serialization X-Git-Url: https://code.kerkeslager.com/?a=commitdiff_plain;h=0bc1ffa1b3ab590b06cc172a86b5a185324e878c;p=sandbox Binary object serialization --- 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', ), ]