use as_bytes function to reduce code duplication, and for later usage

This commit is contained in:
protolambda 2019-07-12 22:11:33 +02:00
parent 619b2a3573
commit b98679957b
No known key found for this signature in database
GPG Key ID: EC89FDBB2B4C7623
2 changed files with 16 additions and 14 deletions

View File

@ -41,15 +41,13 @@ def serialize(obj: SSZValue):
if isinstance(obj, BasicValue):
return serialize_basic(obj)
elif isinstance(obj, Bitvector):
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)
return obj.as_bytes()
elif isinstance(obj, Bitlist):
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)
as_bytearray = list(obj.as_bytes())
if len(obj) % 8 == 0:
as_bytearray.append(1)
else:
as_bytearray[len(obj) // 8] |= 1 << (len(obj) % 8)
return bytes(as_bytearray)
elif isinstance(obj, Series):
return encode_series(obj)
@ -97,11 +95,10 @@ 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, 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)
elif isinstance(values, Bits):
# packs the bits in bytes, left-aligned.
# Exclusive length delimiting bits for bitlists.
return values.as_bytes()
return b''.join([serialize_basic(value) for value in values])

View File

@ -354,7 +354,12 @@ class BitElementsType(ElementsType):
class Bits(BaseList, metaclass=BitElementsType):
pass
def as_bytes(self):
as_bytearray = [0] * ((len(self) + 7) // 8)
for i in range(len(self)):
as_bytearray[i // 8] |= int(self[i]) << (i % 8)
return bytes(as_bytearray)
class Bitlist(Bits):