From 193c5dd55873e556874dc0bab14269708dc7bddd Mon Sep 17 00:00:00 2001 From: Arjan Zijderveld <5286904+arjanz@users.noreply.github.com> Date: Thu, 8 Aug 2024 13:45:09 +0200 Subject: [PATCH] Added bytes() conversion of ScaleBytes Accept bytearray in deserialize --- scalecodec/base.py | 7 ++++++- scalecodec/types.py | 12 +++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/scalecodec/base.py b/scalecodec/base.py index 1269f1a..69c3d4d 100644 --- a/scalecodec/base.py +++ b/scalecodec/base.py @@ -101,7 +101,6 @@ def reset(self): """ self.offset = 0 - def copy(self): return ScaleBytes(self.data) @@ -132,6 +131,12 @@ def __add__(self, data): if type(data) is bytearray: return ScaleBytes(self.data + data) + def __bytes__(self): + return self.to_bytes() + + def to_bytes(self): + return bytes(self.data) + def to_hex(self) -> str: """ Return a hex-string (e.g. "0x00") representation of the byte-stream diff --git a/scalecodec/types.py b/scalecodec/types.py index aec12c3..cf98752 100644 --- a/scalecodec/types.py +++ b/scalecodec/types.py @@ -735,9 +735,9 @@ def serialize(self, value: Union[list, bytes]) -> Union[list, str]: else: return f'0x{value.hex()}' - def deserialize(self, value: Union[list, str, bytes]) -> Union[list, bytes]: + def deserialize(self, value: Union[list, str, bytes, bytearray]) -> Union[list, bytes]: - if type(value) not in [list, str, bytes]: + if type(value) not in [list, str, bytes, bytearray]: raise ScaleDeserializeException('value should be of type list, str or bytes') if type(value) is str: @@ -749,6 +749,9 @@ def deserialize(self, value: Union[list, str, bytes]) -> Union[list, bytes]: if len(value) != self.length: raise ScaleDeserializeException('Length of array does not match size of value') + if type(value) is bytearray: + value = bytes(value) + if type(value) is bytes: if self.type_def is not U8: raise ScaleDeserializeException('Only an Array of U8 can be represented as (hex)bytes') @@ -950,10 +953,13 @@ def _encode(self, value: Union[str, bytes]) -> ScaleBytes: def serialize(self, value: bytes) -> str: return f'0x{value.hex()}' - def deserialize(self, value: Union[str, bytes]) -> bytes: + def deserialize(self, value: Union[str, bytes, bytearray]) -> bytes: if type(value) is str: value = bytes.fromhex(value[2:]) + if type(value) is bytearray: + value = bytes(value) + if type(value) is not bytes: raise ScaleDeserializeException('value should be of type str or bytes')