mirror of
https://github.com/status-im/eth2.0-specs.git
synced 2025-01-19 23:19:28 +00:00
use as_bytes function to reduce code duplication, and for later usage
This commit is contained in:
parent
619b2a3573
commit
b98679957b
@ -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])
|
||||
|
||||
|
||||
|
@ -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):
|
||||
|
Loading…
x
Reference in New Issue
Block a user