From 6422acdcdd80afc3ffbf88fb6cdafecbb7c1eea7 Mon Sep 17 00:00:00 2001 From: Dankrad Feist Date: Wed, 3 Jul 2019 13:31:03 +0100 Subject: [PATCH] Cosmetic change: Define Bitlist/Bitvector serialization using bytes, not bigints --- .../pyspec/eth2spec/utils/ssz/ssz_impl.py | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/test_libs/pyspec/eth2spec/utils/ssz/ssz_impl.py b/test_libs/pyspec/eth2spec/utils/ssz/ssz_impl.py index d5855a755..a4abef966 100644 --- a/test_libs/pyspec/eth2spec/utils/ssz/ssz_impl.py +++ b/test_libs/pyspec/eth2spec/utils/ssz/ssz_impl.py @@ -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])