Skip to content

Commit b6d2abb

Browse files
committed
Added ScaleSerializeException
Added Enum and Struct data validation
1 parent ddb5caa commit b6d2abb

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

scalecodec/exceptions.py

+4
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,7 @@ class ScaleEncodeException(ValueError):
3737

3838
class ScaleDeserializeException(ValueError):
3939
pass
40+
41+
42+
class ScaleSerializeException(ValueError):
43+
pass

scalecodec/types.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,16 @@
1313
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
16+
import enum
1617

1718
import math
1819
import struct
1920
from typing import Union, Optional
2021

2122
from scalecodec.base import ScaleType, ScaleBytes, ScalePrimitive, ScaleTypeDef
2223
from scalecodec.constants import TYPE_DECOMP_MAX_RECURSIVE
23-
from scalecodec.exceptions import ScaleEncodeException, ScaleDecodeException, ScaleDeserializeException
24+
from scalecodec.exceptions import ScaleEncodeException, ScaleDecodeException, ScaleDeserializeException, \
25+
ScaleSerializeException
2426

2527

2628
class UnsignedInteger(ScalePrimitive):
@@ -230,6 +232,8 @@ def decode(self, data) -> dict:
230232
return value
231233

232234
def serialize(self, value: dict) -> dict:
235+
if value is None:
236+
raise ScaleSerializeException('Value cannot be None')
233237
return {k: obj.value for k, obj in value.items()}
234238

235239
def deserialize(self, value: dict) -> dict:
@@ -400,6 +404,12 @@ def deserialize(self, value: Union[str, dict]) -> tuple:
400404
if type(value) is str:
401405
value = {value: None}
402406

407+
if isinstance(value, enum.Enum):
408+
value = {value.name: None}
409+
410+
if len(list(value.items())) != 1:
411+
raise ScaleDeserializeException("Only one variant can be specified for enums")
412+
403413
enum_key, enum_value = list(value.items())[0]
404414

405415
for idx, (variant_name, variant_obj) in enumerate(self.variants.items()):

0 commit comments

Comments
 (0)