~martijnbraam/bare-py

322e8d647a192e4ffa9111102a53007201830052 — Martijn Braam 8 months ago eb85f7d
Simplified pack for unions
2 files changed, 9 insertions(+), 20 deletions(-)

M bare/__init__.py
M example/schema.py
M bare/__init__.py => bare/__init__.py +7 -18
@@ 264,30 264,19 @@ def _unpack_type(ast_node, instance, module, data, offset):
        raise NotImplementedError("{} is not implemented for decoding".format(ast_node))


def pack(instance, member=None):
def pack(instance, unionclass=None):
    """
    Pack an instance of a BARE class into bytes
    :param instance: object to get the schema and data from
    :param member: if the instance is a union, this is the object to get the data and sub-schema from
    :return: bytes
    """
    if member is None:
        ast = instance._ast
        module = sys.modules[instance.__class__.__module__]
        return _pack_type(ast, instance, module)
    else:
        ast = member._ast
        module = sys.modules[member.__class__.__module__]
        untagged = _pack_type(ast, member, module)
        for type in instance._ast.types:
            if type.type.name == member.__class__.__name__:
                index = type.value
                break
        else:
            raise ValueError("{} is not a member of {}".format(member.__class__.__name__, instance.__name__))
        tag = bytes()
        tag += _pack_primitive(BarePrimitive(TypeKind.UINT), index)
        return tag + untagged
    ast = instance._ast
    module = sys.modules[instance.__class__.__module__]

    if unionclass is not None:
        return _pack_type(unionclass._ast, instance, module)
    return _pack_type(ast, instance, module)


def unpack(instance, data, offset=0, primitive=False):

M example/schema.py => example/schema.py +2 -2
@@ 129,7 129,7 @@ class Person:

    @classmethod
    def pack(cls, member):
        return bare.pack(cls, member)
        return bare.pack(member, cls)

    @classmethod
    def unpack(cls, data, offset=0):


@@ 184,7 184,7 @@ class AddressMaybe:

    @classmethod
    def pack(cls, member):
        return bare.pack(cls, member)
        return bare.pack(member, cls)

    @classmethod
    def unpack(cls, data, offset=0):