Cosmetic change: Define Bitlist/Bitvector serialization using bytes, not bigints

This commit is contained in:
Dankrad Feist 2019-07-03 13:31:03 +01:00
parent a63de3dc37
commit 6422acdcdd
No known key found for this signature in database
GPG Key ID: 6815E6A20BEBBABA
1 changed files with 14 additions and 10 deletions

View File

@ -41,11 +41,16 @@ def serialize(obj: SSZValue):
if isinstance(obj, BasicValue):
return serialize_basic(obj)
elif isinstance(obj, Bitvector):
as_integer = sum([obj[i] << i for i in range(len(obj))])
return as_integer.to_bytes((len(obj) + 7) // 8, "little")
as_bytearray = [0] * ((len(obj) + 7) // 8)
for i in range(len(obj)):
as_bytearray[i // 8] |= obj[i] << (i % 8)
return bytes(as_bytearray)
elif isinstance(obj, Bitlist):
as_integer = (1 << len(obj)) + sum([obj[i] << i for i in range(len(obj))])
return as_integer.to_bytes((as_integer.bit_length() + 7) // 8, "little")
as_bytearray = [0] * (len(obj) // 8 + 1)
for i in range(len(obj)):
as_bytearray[i // 8] |= obj[i] << (i % 8)
as_bytearray[len(obj) // 8] |= 1 << (len(obj) % 8)
return bytes(as_bytearray)
elif isinstance(obj, Series):
return encode_series(obj)
else:
@ -92,12 +97,11 @@ def encode_series(values: Series):
def pack(values: Series):
if isinstance(values, bytes): # Bytes and BytesN are already packed
return values
elif isinstance(values, Bitvector):
as_integer = sum([values[i] << i for i in range(len(values))])
return as_integer.to_bytes((values.length + 7) // 8, "little")
elif isinstance(values, Bitlist):
as_integer = sum([values[i] << i for i in range(len(values))])
return as_integer.to_bytes((values.length + 7) // 8, "little")
elif isinstance(values, Bitvector) or isinstance(values, Bitlist):
as_bytearray = [0] * ((len(values) + 7) // 8)
for i in range(len(values)):
as_bytearray[i // 8] |= values[i] << (i % 8)
return bytes(as_bytearray)
return b''.join([serialize_basic(value) for value in values])