Skip to content

Commit 193c5dd

Browse files
committed
Added bytes() conversion of ScaleBytes
Accept bytearray in deserialize
1 parent b6d2abb commit 193c5dd

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

scalecodec/base.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ def reset(self):
101101
"""
102102
self.offset = 0
103103

104-
105104
def copy(self):
106105
return ScaleBytes(self.data)
107106

@@ -132,6 +131,12 @@ def __add__(self, data):
132131
if type(data) is bytearray:
133132
return ScaleBytes(self.data + data)
134133

134+
def __bytes__(self):
135+
return self.to_bytes()
136+
137+
def to_bytes(self):
138+
return bytes(self.data)
139+
135140
def to_hex(self) -> str:
136141
"""
137142
Return a hex-string (e.g. "0x00") representation of the byte-stream

scalecodec/types.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -735,9 +735,9 @@ def serialize(self, value: Union[list, bytes]) -> Union[list, str]:
735735
else:
736736
return f'0x{value.hex()}'
737737

738-
def deserialize(self, value: Union[list, str, bytes]) -> Union[list, bytes]:
738+
def deserialize(self, value: Union[list, str, bytes, bytearray]) -> Union[list, bytes]:
739739

740-
if type(value) not in [list, str, bytes]:
740+
if type(value) not in [list, str, bytes, bytearray]:
741741
raise ScaleDeserializeException('value should be of type list, str or bytes')
742742

743743
if type(value) is str:
@@ -749,6 +749,9 @@ def deserialize(self, value: Union[list, str, bytes]) -> Union[list, bytes]:
749749
if len(value) != self.length:
750750
raise ScaleDeserializeException('Length of array does not match size of value')
751751

752+
if type(value) is bytearray:
753+
value = bytes(value)
754+
752755
if type(value) is bytes:
753756
if self.type_def is not U8:
754757
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:
950953
def serialize(self, value: bytes) -> str:
951954
return f'0x{value.hex()}'
952955

953-
def deserialize(self, value: Union[str, bytes]) -> bytes:
956+
def deserialize(self, value: Union[str, bytes, bytearray]) -> bytes:
954957
if type(value) is str:
955958
value = bytes.fromhex(value[2:])
956959

960+
if type(value) is bytearray:
961+
value = bytes(value)
962+
957963
if type(value) is not bytes:
958964
raise ScaleDeserializeException('value should be of type str or bytes')
959965

0 commit comments

Comments
 (0)