Skip to content

Commit

Permalink
Added bytes() conversion of ScaleBytes
Browse files Browse the repository at this point in the history
Accept bytearray in deserialize
  • Loading branch information
arjanz committed Aug 8, 2024
1 parent b6d2abb commit 193c5dd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
7 changes: 6 additions & 1 deletion scalecodec/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ def reset(self):
"""
self.offset = 0


def copy(self):
return ScaleBytes(self.data)

Expand Down Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions scalecodec/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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')
Expand Down Expand Up @@ -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')

Expand Down

0 comments on commit 193c5dd

Please sign in to comment.