Rewrote serializer type length
This commit is contained in:
@@ -15,7 +15,7 @@ TYPE_FLOAT = b"f", 4
|
||||
TYPE_DOUBLE = b"d", 8
|
||||
TYPE_STRING = b"s", 1
|
||||
|
||||
TYPE_ULEB = 1 # Just so we have the enum type~ish
|
||||
TYPE_ULEB = b"s", 1, True # True just so they are different tuples
|
||||
|
||||
BYTEORDER_NATIVE = b"@"
|
||||
BYTEORDER_LITTLE = b"<"
|
||||
@@ -80,11 +80,11 @@ def read(value_type, stream):
|
||||
struct.unpack(value_type[0], stream[:value_type[1]])
|
||||
|
||||
class Serializable:
|
||||
length = None
|
||||
prefix = b""
|
||||
pre_serialized = None
|
||||
length = None
|
||||
prefix = b""
|
||||
filter = None
|
||||
|
||||
def __init__(self, value, type = None, length = None, prefix = b"", pre = None):
|
||||
def __init__(self, value, type = None, length = None, prefix = b"", filter = None):
|
||||
self.value = value
|
||||
|
||||
if type is not None:
|
||||
@@ -94,34 +94,44 @@ class Serializable:
|
||||
|
||||
self.length = length
|
||||
self.prefix = prefix
|
||||
self.pre_serialized = pre
|
||||
self.filter = filter
|
||||
|
||||
def get_struct_fmt(self):
|
||||
def get_struct_fmt(self, length = 1):
|
||||
struct_fmt = self.type[0]
|
||||
if length > 1:
|
||||
struct_fmt = b"%d%b" % (length, self.type[0])
|
||||
if self.length is not None:
|
||||
return b"%d%b" % (self.length.value, self.type[0])
|
||||
return self.type[0]
|
||||
if self.length == TYPE_ULEB:
|
||||
val = self.get_value()
|
||||
struct_fmt = b"%d%b%b" % (len(val[0]), self.length[0], struct_fmt)
|
||||
else:
|
||||
struct_fmt = b"%b%b" % (self.length[0], struct_fmt)
|
||||
return struct_fmt
|
||||
|
||||
def get_value(self):
|
||||
val = self.value
|
||||
if self.pre_serialized is not None:
|
||||
val[-1] = self.pre_serialized(val[-1])
|
||||
val = [self.value]
|
||||
if self.filter is not None:
|
||||
val[-1] = self.filter(val[-1])
|
||||
if self.length is not None:
|
||||
if self.length == TYPE_ULEB:
|
||||
val.insert(0, encode_uleb(len(val[-1])))
|
||||
else:
|
||||
val.insert(0, len(val[-1]))
|
||||
return val
|
||||
|
||||
def pack(self, byte_order = BYTEORDER_LITTLE):
|
||||
if self.type == TYPE_ULEB:
|
||||
return encode_uleb(self.value)
|
||||
struct_fmt = byte_order + self.get_struct_fmt()
|
||||
packed = struct.pack(struct_fmt, self.get_value())
|
||||
length = 1
|
||||
if self.type == TYPE_STRING:
|
||||
length = len(self.get_value()[-1])
|
||||
struct_fmt = byte_order + self.get_struct_fmt(length)
|
||||
packed = struct.pack(struct_fmt, *self.get_value())
|
||||
if self.prefix is not None:
|
||||
packed = self.prefix + packed
|
||||
return packed
|
||||
|
||||
def unpack(self, length = -1, byte_order = BYTEORDER_LITTLE):
|
||||
if self.type == TYPE_ULEB:
|
||||
self.value = decode_uleb(2)
|
||||
return
|
||||
if self.type == TYPE_STRING:
|
||||
length =
|
||||
length = len(self.value)
|
||||
struct_fmt = byte_order + self.get_struct_fmt(length)
|
||||
|
||||
class Serializer:
|
||||
|
||||
Reference in New Issue
Block a user