Added serialization for tag-only types
[sandbox] / serial / binary.py
1 import collections
2
3 TAG_NULL = 0x00
4 TAG_TRUE = 0x01
5 TAG_FALSE = 0x02
6
7 TaggedObject = collections.namedtuple(
8     'TaggedObject',
9     [
10         'tag',
11         'instance',
12     ],
13 )
14
15 def _make_tag_only_serializer(tag, expected_value):
16     tag = bytes([tag])
17
18     def serializer(to):
19         assert to.instance == expected_value
20         return tag
21
22     return serializer
23
24 _TAGS_TO_SERIALIZERS = {
25     TAG_NULL: _make_tag_only_serializer(TAG_NULL, None),
26     TAG_TRUE: _make_tag_only_serializer(TAG_TRUE, True),
27     TAG_FALSE: _make_tag_only_serializer(TAG_FALSE, False),
28 }
29
30 def serialize(to):
31     return _TAGS_TO_SERIALIZERS[to.tag](to)
32
33 def _make_tag_only_parser(tag, value):
34     def parser(b):
35         return TaggedObject(tag = tag, instance = value), b
36
37     return parser
38
39 _TAGS_TO_PARSERS = {
40     TAG_NULL: _make_tag_only_parser(TAG_NULL, None),
41     TAG_TRUE: _make_tag_only_parser(TAG_TRUE, True),
42     TAG_FALSE: _make_tag_only_parser(TAG_FALSE, False),
43 }
44
45 def deserialize(b):
46     result, remainder = _TAGS_TO_PARSERS[b[0]](b[1:])
47
48     if len(remainder) == 0:
49         return result
50
51     raise Exception('Unable to parse remainder: {}'.format(remainder))