Skip to content

Commit

Permalink
Added ScaleSerializeException
Browse files Browse the repository at this point in the history
Added Enum and Struct data validation
  • Loading branch information
arjanz committed Aug 5, 2024
1 parent ddb5caa commit b6d2abb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 4 additions & 0 deletions scalecodec/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@ class ScaleEncodeException(ValueError):

class ScaleDeserializeException(ValueError):
pass


class ScaleSerializeException(ValueError):
pass
12 changes: 11 additions & 1 deletion scalecodec/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import enum

import math
import struct
from typing import Union, Optional

from scalecodec.base import ScaleType, ScaleBytes, ScalePrimitive, ScaleTypeDef
from scalecodec.constants import TYPE_DECOMP_MAX_RECURSIVE
from scalecodec.exceptions import ScaleEncodeException, ScaleDecodeException, ScaleDeserializeException
from scalecodec.exceptions import ScaleEncodeException, ScaleDecodeException, ScaleDeserializeException, \
ScaleSerializeException


class UnsignedInteger(ScalePrimitive):
Expand Down Expand Up @@ -230,6 +232,8 @@ def decode(self, data) -> dict:
return value

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

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

if isinstance(value, enum.Enum):
value = {value.name: None}

if len(list(value.items())) != 1:
raise ScaleDeserializeException("Only one variant can be specified for enums")

enum_key, enum_value = list(value.items())[0]

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

0 comments on commit b6d2abb

Please sign in to comment.